Roh*_*hit 18 python matplotlib histogram pandas
我想创建以下直方图(见下图)取自"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()
Run Code Online (Sandbox Code Playgroud)
当我使用ax = ax1时,上面的代码不起作用:pandas多个图不能作为组合,也不是这个例子做我需要的:使用pandas覆盖多个直方图.当我按原样使用代码时,它会创建两个带直方图的窗口.任何想法如何结合它们?
以下是我希望看到最终数字的示例:
Pau*_*l H 33
据我所知,大熊猫无法处理这种情况.没关系,因为他们所有的绘图方法都只是为了方便.你需要直接使用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)
Run Code Online (Sandbox Code Playgroud)
这给了我:
Chr*_*eno 21
一个快速的解决方案是使用melt()
from pandas
,然后使用 绘图seaborn
。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# make dataframe
df = pd.DataFrame(np.random.normal(size=(200,2)), columns=['A', 'B'])
# plot melted dataframe in a single command
sns.histplot(df.melt(), x='value', hue='variable',
multiple='dodge', shrink=.75, bins=20);
Run Code Online (Sandbox Code Playgroud)
设置multiple='dodge'
使条形图并排,并使shrink=.75
一对条形图占据整个垃圾箱的 3/4。
为了帮助理解melt()
做了什么,这些是数据框df
和df.melt()
:
lin*_*bug 14
如果有人想在另一个直方图上绘制一个直方图(而不是交替条形图),您可以简单地.hist()
在要绘制的系列上连续调用:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import pandas
np.random.seed(0)
df = pandas.DataFrame(np.random.normal(size=(37,2)), columns=['A', 'B'])
df['A'].hist()
df['B'].hist()
Run Code Online (Sandbox Code Playgroud)
这给你:
请注意,您调用的顺序很.hist()
重要(第一个将在后面)
您制作了两个数据框和一个 matplotlib 轴
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df1 = pd.DataFrame({
'data1': np.random.randn(10),
'data2': np.random.randn(10)
})
df2 = df1.copy()
fig, ax = plt.subplots()
df1.hist(column=['data1'], ax=ax)
df2.hist(column=['data2'], ax=ax)
Run Code Online (Sandbox Code Playgroud)
小智 6
来自pandas网站(http://pandas.pydata.org/pandas-docs/stable/visualization.html#visualization-hist):
df4 = pd.DataFrame({'a': np.random.randn(1000) + 1, 'b': np.random.randn(1000),
'c': np.random.randn(1000) - 1}, columns=['a', 'b', 'c'])
plt.figure();
df4.plot(kind='hist', alpha=0.5)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
36122 次 |
最近记录: |