问题描述
我想创建以下直方图(请参见下图),该直方图取自《 Think Stats》一书.但是,我无法将它们放在同一地块上.每个DataFrame都有其自己的子图.
I would like to create the following histogram (see image below) taken from the book "Think Stats". However, I cannot get them on the same plot. Each DataFrame takes its own subplot.
我有以下代码:
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时,以上代码不起作用:,也不是我需要的这个示例:.当我按原样使用代码时,它将创建两个带有直方图的窗口.有什么想法如何将它们结合起来吗?
The above code does not work when I use ax = ax1 as suggested in: pandas multiple plots not working as hists nor this example does what I need: Overlaying multiple histograms using pandas. When I use the code as it is, it creates two windows with histograms. Any ideas how to combine them?
以下是我希望最终人物看起来如何的一个示例:
Here's an example of how I'd like the final figure to look:
推荐答案
据我所知,大熊猫无法应对这种情况.可以,因为它们的所有绘制方法仅是为了方便.您需要直接使用matplotlib.这是我的方法:
As far as I can tell, pandas can't handle this situation. That's ok since all of their plotting methods are for convenience only. You'll need to use matplotlib directly. Here's how I do it:
%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)
这给了我:
这篇关于 pandas 中的多个直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!