【问题标题】:How do I plot a bar graph using Pandas?如何使用 Pandas 绘制条形图?
【发布时间】:2017-08-27 22:28:27
【问题描述】:

我有这样的熊猫数据框

a  b  c  d  e  f  label
1  3  4  5  6  7    1
2  2  5  7  5  7    0
4  7  9  0  8  7    1
6  9  4  7  3  8    1
7  0  9  8  7  6    0

我想要一个看起来像这样的条形图 - :

我曾尝试使用 pandas 中的 hist() 函数,但我无法弄清楚如何在条形图中包含标签以获得如下图,就像图像中的那样。

【问题讨论】:

  • 也许显示创建示例输入的命令很有用,这样我们就可以轻松地自己构建数据框并测试输出是否正确。
  • 考虑你有上面的数据框。我用过

标签: python pandas matplotlib data-science


【解决方案1】:

我认为您需要 pivot 并按 cumcount 计数 最后一次通话DataFrame.plot.bar:

df = pd.pivot(index=df.groupby('label').cumcount(), columns=df.label, values=df.a).fillna(0)
print (df)
label    0    1
0      2.0  1.0
1      7.0  4.0
2      0.0  6.0

df.plot.bar()

或者可能需要聚合 size 并由 unstack 重塑:

df = df.groupby(['label', 'a']).size().unstack(0, fill_value=0)

df.plot.bar()

使用piRSquared 数据获得更好的样本:

【讨论】:

  • 很酷 :-) 感谢您提出可视化 :)
【解决方案2】:

试试

df.groupby('label').a.value_counts().unstack(0, fill_value=0).plot.bar()

考虑数据框df

np.random.seed([3,1415])
df = pd.DataFrame(
    np.random.randint(10, size=(50, 6)),
    columns=list('abcdef')
).assign(label=np.random.randint(2, size=50))

print(df.head())

   a  b  c  d  e  f  label
0  0  2  7  3  8  7      0
1  0  6  8  6  0  2      0
2  0  4  9  7  3  2      0
3  4  3  3  6  7  7      0
4  4  5  3  7  5  9      1

演示

df.groupby('label').a.value_counts().unstack(0, fill_value=0).plot.bar()

【讨论】:

  • 它起作用了:-) df.groupby('label').a.value_counts().unstack(0, fill_value=0).plot.bar() 关于这一行,你是否建议阅读了解 value_counts() 函数的内容?
  • @NiranjanAgnihotri value_counts
  • 如果我要为数据集中的所有属性动态绘制相似的图表,我们在代码 df.groupby('label').a.value_counts() 行中使用了属性名称.unstack(0, fill_value=0).plot.bar() 如何为所有属性动态执行此操作?将属性名称作为字符串变量不起作用
  • @NiranjanAgnihotri df.groupby('label')['col_name'].value_counts().unstack(0, fill_value=0).plot.bar()
  • 工作:-) 问候
猜你喜欢
  • 2017-04-11
  • 2019-04-12
  • 2015-06-12
  • 2016-05-24
  • 2021-07-07
  • 2016-03-18
相关资源
最近更新 更多