【问题标题】:plot serveral pandas columns as "y" in seaborn barplot [duplicate]在seaborn barplot中将几个熊猫列绘制为“y”[重复]
【发布时间】:2021-05-06 12:06:30
【问题描述】:

我想用 seaborn 创建条形图,它将显示 pandas 数据框中三列的平均值 我的数据框与此类似:

>>>name      treatment    weight    height   ind1
0  Miki      93A control  77.5      23.2     105.5
1  Lorense   75B high     35.1      25.1     57.3
2  Derek     93A high     74.3      26.4     94.5
3  Lily      24C medium   12.2      14.4     26.8
4  Tim       75B high     37.2      26.4     55.1
...

我想获得将处理作为 x 轴的条形图,将体重、高度和 ind1 作为条形。并在此显示错误。

我曾尝试简单地使用 seaborn,但它仅在我尝试绘制变量(例如重量、hright 或 ind1)时才有效,但不允许我添加多个“变量”:

ax = sns.barplot(x="treatments", y="weight", data=df)

(结果说明:):

我尝试为 y 创建变量列表,例如 matplotlib :

ax = sns.barplot(x="Treat Name alias", y=["weight","height","ind1"], data=df)

然后我收到错误消息:

ValueError:DataFrame 的真值不明确。使用a.empty, a.bool()、a.item()、a.any() 或 a.all()。

问题是我希望有多个列作为 y 值。我已经看到了 catplot 选项,但似乎它们将特定列分组,而不是将每一列绘制为具有相同 x 轴的 y 值。

我想要的输出将是将处理作为 x 轴,然后每个处理具有三个条,一个用于体重,一个用于高度,一个用于 ind1。并获得标准图(条形图上的“黑线”)。

【问题讨论】:

  • @anky 创建具有长 x 轴的 hige 图表,其中处理重复多次且未出现错误。我想使用 te seaborn 包以便轻松出错。
  • 知道了:seaborn multiple variables group bar plot 已在此处回答,如果您需要其他内容,请告诉我并编辑问题。对于你的问题。所有解决方案都有效。
  • bdw 我的意思是:df.groupby("treatment",sort=False).mean().plot.bar() :) 抱歉,没有看到标准要求。

标签: python pandas seaborn bar-chart


【解决方案1】:

首先你需要重塑你的数据框

df = df.melt(id_vars=['name', 'treatment'], var_name='measurement', value_name='mean')

导致...

   name treatment measurement   mean
0   93A   control      weight   77.5
1   75B      high      weight   35.1
2   93A      high      weight   74.3
3   24C    medium      weight   12.2
4   75B      high      weight   37.2
5   93A   control      height   23.2
6   75B      high      height   25.1
7   93A      high      height   26.4
8   24C    medium      height   14.4
9   75B      high      height   26.4
10  93A   control        ind1  105.5
11  75B      high        ind1   57.3
12  93A      high        ind1   94.5
13  24C    medium        ind1   26.8
14  75B      high        ind1   55.1

现在,当您在 seaborn 中绘制它时,您将在一列“内”有多个变量,因此您可以这样称呼它...

g = sns.catplot(
    data=df, kind="bar",
    x="treatment", y="mean", hue="measurement",
    ci="sd", palette='colorblind', alpha=.6, height=6
)

这会给你...

【讨论】:

    猜你喜欢
    • 2015-10-06
    • 2018-12-15
    • 2019-04-05
    • 2020-03-18
    • 2017-09-16
    • 2020-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多