Pandas:在同一个图上绘制两个直方图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26911973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas: plotting two histograms on the same plot
提问by meto
I would like to have 2 histograms to appear on the same plot (with different colors, and possibly differente alphas). I tried
我希望有 2 个直方图出现在同一个图上(具有不同的颜色,并且可能具有不同的 alpha)。我试过
import random
x = pd.DataFrame([random.gauss(3,1) for _ in range(400)])
y = pd.DataFrame([random.gauss(4,2) for _ in range(400)])
x.hist( alpha=0.5, label='x')
y.hist(alpha=0.5, label='y')
x.plot(kind='kde', style='k--')
y.plot(kind='kde', style='k--')
plt.legend(loc='upper right')
plt.show()
This produces the result in 4 different plots. How can I have them on the same one?
这会在 4 个不同的图中产生结果。我怎么能把它们放在同一个上面?
回答by rustil
If I understood correctly, both hists should go into the same subplot. So it should be
如果我理解正确,两个历史应该进入同一个子图。所以应该是
fig = plt.figure()
ax = fig.add_subplot(111)
_ = ax.hist(x.values)
_ = ax.hist(y.values, color='red', alpha=.3)
You can also pass the pandas plot method an axis object, so if you want both kde's in another plot do:
您还可以将 pandas 绘图方法传递给轴对象,因此如果您希望在另一个绘图中同时使用两个 kde,请执行以下操作:
fig = plt.figure()
ax = fig.add_subplot(111)
x.plot(kind='kde', ax=ax)
y.plot(kind='kde', ax=ax, color='red')
To get everything into a single plot you need two different y-scales since kde is density and histogram is frequency. For that you use the axes.twinx()command.
要将所有内容整合到一个图中,您需要两个不同的 y 尺度,因为 kde 是密度,直方图是频率。为此,您使用axes.twinx()命令。
fig = plt.figure()
ax = fig.add_subplot(111)
_ = ax.hist(x.values)
_ = ax.hist(y.values, color='red', alpha=.3)
ax1 = ax.twinx()
x.plot(kind='kde', ax=ax1)
y.plot(kind='kde', ax=ax1, color='red')
回答by polku
You can use plt.figure() and the function add_subplot(): the first 2 arguments are the number of rows and cols you want in your plot, the last is the position of the subplot in the plot.
您可以使用 plt.figure() 和函数 add_subplot():前 2 个参数是绘图中所需的行数和列数,最后一个是绘图中子图的位置。
fig = plt.figure()
subplot = fig.add_subplot(1, 2, 1)
subplot.hist(x.ix[:,0], alpha=0.5)
subplot = fig.add_subplot(1, 2, 2)
subplot.hist(y.ix[:,0], alpha=0.5)

