首页 > 解决方案 > 在python中叠加两个单独的直方图

问题描述

我有两个单独的数据框,我将它们制作成直方图,我想知道如何覆盖它们,因此对于 x 轴上的每个类别,条形图对于每个数据框都是不同的颜色。这是我用于单独条形图的代码。

df1.plot.bar(x='brand', y='desc')
df2.groupby(['brand']).count()['desc'].plot(kind='bar')

我试过这段代码:

previous = df1.plot.bar(x='brand', y='desc')
current= df2.groupby(['brand']).count()['desc'].plot(kind='bar')
bins = np.linspace(1, 4)

plt.hist(x, bins, alpha=0.9,normed=1, label='Previous')
plt.hist(y, bins, alpha=0.5, normed=0,label='Current')
plt.legend(loc='upper right')
plt.show()

此代码未正确覆盖图形。问题是数据框 2 没有数值,所以我需要使用 count 方法。感谢帮助!

标签: pythondataframematplotlib

解决方案


您可能必须在 matplotlib 中使用轴对象。简单来说,您创建一个图形,其中包含一些与之关联的轴对象,然后您可以从中调用 hist。这是您可以做到的一种方法:

fig, ax = plt.subplots(1, 1)

ax.hist(x, bins, alpha=0.9,normed=1, label='Previous')
ax.hist(y, bins, alpha=0.5, normed=0,label='Current')
ax.legend(loc='upper right')

plt.show()

推荐阅读