python - Pandas 中的多个直方图

标签 python matplotlib pandas histogram

我想创建以下直方图(见下图),取自“Think Stats”一书。但是,我不能让他们在同一个情节上。每个 DataFrame 都有自己的子图。

我有以下代码:

import nsfg
import matplotlib.pyplot as plt
df = nsfg.ReadFemPreg()
preg = nsfg.ReadFemPreg()
live = preg[preg.outcome == 1]

first = live[live.birthord == 1]
others = live[live.birthord != 1]

#fig = plt.figure()
#ax1 = fig.add_subplot(111)

first.hist(column = 'prglngth', bins = 40, color = 'teal', \
           alpha = 0.5)
others.hist(column = 'prglngth', bins = 40, color = 'blue', \
            alpha = 0.5)
plt.show()

当我按照以下建议使用 ax = ax1 时,上面的代码不起作用:pandas multiple plots not working as hists这个例子也不能满足我的需要:Overlaying multiple histograms using pandas .当我按原样使用代码时,它会创建两个带有直方图的窗口。任何想法如何组合它们?

以下是我希望最终图形看起来如何的示例: enter image description here

最佳答案

据我所知,pandas 无法处理这种情况。没关系,因为他们所有的绘图方法都只是为了方便。您需要直接使用 matplotlib。这是我的做法:

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import pandas
#import seaborn
#seaborn.set(style='ticks')

np.random.seed(0)
df = pandas.DataFrame(np.random.normal(size=(37,2)), columns=['A', 'B'])
fig, ax = plt.subplots()

a_heights, a_bins = np.histogram(df['A'])
b_heights, b_bins = np.histogram(df['B'], bins=a_bins)

width = (a_bins[1] - a_bins[0])/3

ax.bar(a_bins[:-1], a_heights, width=width, facecolor='cornflowerblue')
ax.bar(b_bins[:-1]+width, b_heights, width=width, facecolor='seagreen')
#seaborn.despine(ax=ax, offset=10)

这给了我: enter image description here

关于python - Pandas 中的多个直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25539195/

相关文章:

python - 从行到列构建数据集 pandas python

python - Matplotlib 箱线图传单未显示

python - 将 Python 函数应用于 Pandas 分组数据帧 - 加速计算的最有效方法是什么?

python - 巴特沃斯滤波器 - 输出 x (-1)?

python - 为什么 Python 不能打印 Unicode 符号?

python - Matplotlib:用数组调用绘图函数有什么作用?

python-3.x - 如何将交互式 matplotlib 图形插入 tkinter Canvas

python - 在 Python 中建模 4-D 数据(带时间戳)

python - Django:我的 models.py 文件似乎无法同步到数据库。

python - 使用 Python 减少对列表