如何在 1 个图中组合 2 个数据框直方图? [英] How to combine 2 dataframe histograms in 1 plot?
问题描述
我想使用显示数据框中所有直方图的代码.那将是 df.hist(bins=10)
.但是,我想添加另一个显示CDF的直方图 df_hist = df.hist(cumulative = True,bins = 100,density = 1,histtype ="step")
I would like to use a code that shows all histograms in a dataframe. That will be df.hist(bins=10)
. However, I would like to add another histograms which shows CDF df_hist=df.hist(cumulative=True,bins=100,density=1,histtype="step")
我尝试使用 fig = plt.figure()
和 plt.subplot(211)
.但是,此df.hist实际上是pandas函数的一部分,而不是matplotlib函数的一部分.我还尝试设置轴,并向每个直方图添加ax = ax1和ax2选项,但这没有用.
I tried separating their matplotlib axes by using fig=plt.figure()
and
plt.subplot(211)
. But this df.hist is actually part of pandas function, not matplotlib function. I also tried setting axes and adding ax=ax1 and ax2 options to each histogram but it didn't work.
如何将这些直方图组合在一起?有什么帮助吗?
How can I combine these histograms together? Any help?
我想要组合的直方图是这样的.我想并排展示它们,或将第二个放在第一个的顶端.对不起,我不在乎让它们看起来不错.
Histograms that I want to combine are like these. I want to show them side by side or put the second one on tip of the first one. Sorry that I didn't care to make them look good.
推荐答案
可以将它们绘制在一起:
It is possible to draw them together:
# toy data frame
df = pd.DataFrame(np.random.normal(0,1,(100,20)))
# draw hist
fig, axes = plt.subplots(5,4, figsize=(16,10))
df.plot(kind='hist', subplots=True, ax=axes, alpha=0.5)
# clone axes so they have different scales
ax_new = [ax.twinx() for ax in axes.flatten()]
df.plot(kind='kde', ax=ax_new, subplots=True)
plt.show()
输出:
还可以并排绘制它们.例如
It's also possible to draw them side-by-side. For example
fig, axes = plt.subplots(10,4, figsize=(16,10))
hist_axes = axes.flatten()[:20]
df.plot(kind='hist', subplots=True, ax=hist_axes, alpha=0.5)
kde_axes = axes.flatten()[20:]
df.plot(kind='kde', subplots=True, ax=kde_axes, alpha=0.5)
将在kde上绘制历史记录.
will plot hist on top of kde.
这篇关于如何在 1 个图中组合 2 个数据框直方图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!