简体   繁体   English

在python中叠加两个单独的直方图

[英]Overlay two separate histograms in python

I have two separate dataframes that I made into histograms and I want to know how I can overlay them so for each category in the x axis the bar is a different color for each dataframe.我有两个单独的数据框,我制作了直方图,我想知道如何覆盖它们,因此对于 x 轴上的每个类别,每个数据框的条形都是不同的颜色。 This is the code I have for the separate bar graphs.这是我用于单独条形图的代码。

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

I tried this code:我试过这个代码:

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

This code is not overlaying the graphs properly.此代码未正确覆盖图形。 The problem is dataframe 2 doesn't have numeric values so i need to use the count method.问题是数据框 2 没有数值,所以我需要使用计数方法。 Appreciate the help!感谢帮助!

You might have to use axes objects in matplotlib.您可能必须在 matplotlib 中使用轴对象。 In simple terms, you create a figure with some axes object associated with it, then you can call hist from it.简单来说,您创建了一个图形,其中包含一些与之关联的轴对象,然后您可以从中调用 hist。 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()

Make use of seaborn's histogram with several variables .使用带有多个变量的 seaborn 直方图 In your case it would be:在您的情况下,它将是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM