如何将 2 个数据帧直方图合并到 1 个图中?

2024-03-16

我想使用显示数据框中所有直方图的代码。那将是df.hist(bins=10)。但是,我想添加另一个显示 CDF 的直方图df_hist=df.hist(cumulative=True,bins=100,density=1,histtype="step")

我尝试使用分离他们的 matplotlib 轴fig=plt.figure() and plt.subplot(211)。但这个 df.hist 实际上是 pandas 函数的一部分,而不是 matplotlib 函数。我还尝试设置轴并向每个直方图添加 ax=ax1 和 ax2 选项,但它不起作用。

如何将这些直方图组合在一起? 有什么帮助吗?

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. histogram1 histogram2


可以将它们放在一起:

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

Output:

也可以并排绘制它们。例如

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 之上绘制 hist。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 2 个数据帧直方图合并到 1 个图中? 的相关文章

随机推荐