pandas :在同一图上绘制两个直方图 [英] Pandas: plotting two histograms on the same plot

查看:102
本文介绍了 pandas :在同一图上绘制两个直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让2个直方图出现在同一图上(具有不同的颜色,并且可能具有不同的alpha).我尝试过

I would like to have 2 histograms to appear on the same plot (with different colors, and possibly differente alphas). I tried

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

这将在4个不同的图中产生结果.我怎样才能让他们同一个?

This produces the result in 4 different plots. How can I have them on the same one?

推荐答案

如果我正确理解,则两个提示都应放在同一子图中.所以应该是

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)

您还可以将pandas plot方法传递给轴对象,因此,如果您希望两个kde都在另一个图中执行:

You can also pass the pandas plot method an axis object, so if you want both kde's in another plot do:

fig = plt.figure()
ax = fig.add_subplot(111)
x.plot(kind='kde', ax=ax)
y.plot(kind='kde', ax=ax, color='red')

由于kde是密度,直方图是频率,因此要使所有内容成一个图,您需要两个不同的y比例尺.为此,您可以使用axes.twinx()命令.

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.

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

这篇关于 pandas :在同一图上绘制两个直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆