使用matplotlib在一个子图中从 pandas DataFrame绘制两个直方图 [英] Plotting two histograms from a pandas DataFrame in one subplot using matplotlib
本文介绍了使用matplotlib在一个子图中从 pandas DataFrame绘制两个直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下所示的pandas数据框:
df = pd.DataFrame({ 'a_wood' : np.random.randn(100),
'a_grassland' : np.random.randn(100),
'a_settlement' : np.random.randn(100),
'b_wood' : np.random.randn(100),
'b_grassland' : np.random.randn(100),
'b_settlement' : np.random.randn(100)})
我想用一个子图中的每个数据帧头创建此数据的直方图.
fig, ax = plt.subplots(2, 3, sharex='col', sharey='row')
m=0
for i in range(2):
for j in range(3):
df.hist(column = df.columns[m], bins = 12, ax=ax[i,j], figsize=(20, 18))
m+=1
为此,先前的代码可以完美运行,但现在我想将带眼的a和b标头(例如"a_woods"和"b-woods")组合到一个子图中,因此只有三个直方图.我尝试将两个列分配给df.columns[[m,m+3]]
,但这不起作用.我也有一个索引列,其中包含"day_1"之类的字符串,我希望将其放在x轴上.有人可以帮我吗?
这就是我走了多远.
解决方案
我不知道我是否正确理解了您的问题,但是类似这样的事情可以将这些图结合起来.您可能想在Alpha上玩一些,然后更改标题.
#NOTE that you might want to specify your bins or they wont line up exactly
fig, ax = plt.subplots(1, 3, sharex='col', sharey='row', figsize=(20, 18))
n = 3
for j in range(n):
df.hist(column=df.columns[j], bins=12, ax=ax[j], alpha=0.5, color='red')
df.hist(column=df.columns[j+n], bins=12, ax=ax[j], alpha=0.5, color='blue')
ax[j].set_title(df.columns[j][2:])
要将它们彼此相邻绘制,请尝试以下操作:
#This example doesnt have the issue with different binsizes within one subplot
fig, ax = plt.subplots(1, 3, sharex='col', sharey='row', figsize=(20, 18))
n = 3
colors = ['red', 'blue']
axes = ax.flatten()
for i,j in zip(range(n), axes):
j.hist([df.iloc[:,i], df.iloc[:,i+n]], bins=12, color=colors)
j.set_title(df.columns[i][2:])
查看全文