我想创建以下直方图(见下图),取自“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 .当我按原样使用代码时,它会创建两个带有直方图的窗口。任何想法如何组合它们?
以下是我希望最终图形看起来如何的示例:
最佳答案
据我所知,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)
这给了我:
关于python - Pandas 中的多个直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25539195/