在python中覆盖两个单独的直方图

时间:2018-11-15 14:17:32

标签: python dataframe matplotlib

我有两个单独的数据框,我将它们制成直方图,我想知道如何覆盖它们,因此对于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方法。感谢帮助!

2 个答案:

答案 0 :(得分:1)

You might have to use axes objects in matplotlib. In simple terms, you create a figure with some axes object associated with it, then you can call hist from it. Here's one way you can do it:

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()

答案 1 :(得分:0)

使用seaborn的histogram with several variables。在您的情况下,将是:

import seaborn as sns

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


sns.distplot( previous , color="skyblue", label="previous")
sns.distplot( current , color="red", label="Current")