繁体   English   中英

熊猫:在同一个地块上绘制两个直方图

[英]Pandas: plotting two histograms on the same plot

我想有2个直方图出现在同一个图上(有不同的颜色,可能还有不同的alphas)。 我试过了

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个不同图的结果。 我怎么能把它们放在同一个?

如果我理解正确的话,两个his应该进入同一个子情节。 所以它应该是

fig = plt.figure()
ax = fig.add_subplot(111)
_ = ax.hist(x.values)
_ = ax.hist(y.values, color='red', alpha=.3)

你也可以将pandas plot方法传递给一个轴对象,所以如果你想在另一个图中同时使用kde:

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

要将所有内容放入单个图中,您需要两个不同的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')

您可以使用plt.figure()和函数add_subplot():前两个参数是您在绘图中所需的行数和列数,最后一个是绘图中子图的位置。

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)

暂无
暂无

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

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