我正在尝试使用matplotlib绘制以下数据帧:
df = pd.DataFrame({'X': ["A", "A", "B", "B"], 'Z': ["a", "b", "a", "b"], 'Y': [5, 1, 10, 5]})
df
X Z Y
0 A a 5
1 A b 1
2 B a 10
3 B b 5
我想要的是两个条形图,其中条形图是彼此相邻的,而不是在彼此的顶部。当我运行这段代码时,条形图会一个接一个地放在一起:
plt.barh(df['X'][df['Z'] == "a"], df['Y'][df['Z'] == "a"], color = 'blue')
plt.barh(df['X'][df['Z'] == "b"], df['Y'][df['Z'] == "b"], color = 'red')
当我尝试改变条的位置时,我得到了错误:can only concatenate str (not "float") to str
。我该如何解决这个问题呢?
发布于 2020-01-28 15:46:11
我不确定你到底想要什么,但你可以试试这个:
df.set_index(['X','Z'])['Y'].unstack().plot.barh()
或
df.set_index(['X','Z'])['Y'].unstack().plot.bar()
或
df.set_index(['X','Z'])['Y'].unstack().plot.barh(subplots=True, layout=(1,2))
或
df.set_index(['X','Z'])['Y'].unstack().plot.bar(subplots=True, layout=(1,2))
发布于 2020-01-28 15:39:27
发布于 2020-01-28 15:35:08
在DataFrame.plot.barh
中使用DataFrame.pivot
df.pivot(*df).plot.barh()
或
df.pivot(*df).plot(kind = 'bar')
https://stackoverflow.com/questions/59952078
复制相似问题