使用matplotlib在一个子图中从熊猫DataFrame绘制两个直方图

Max*_*603 3 python matplotlib histogram 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)})
Run Code Online (Sandbox Code Playgroud)

我想用一个子图中的每个数据帧头创建此数据的直方图。

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
Run Code Online (Sandbox Code Playgroud)

为此,以前的代码可以完美地工作,但是现在我想将eyery a和b标头(例如“ a_woods”和“ b-woods”)组合到一个子图中,因此只有三个直方图。我尝试将两个列分配给,df.columns[[m,m+3]]但这不起作用。我也有一个索引列,其中包含类似“ day_1”之类的字符串,我希望将其放在x轴上。有人能帮我吗?

这就是我走了多远。 直方图

Eri*_*ric 7

您想要循环遍历每一列并将其数据绘制在直方图中的东西,对吗?我可以建议你做一些修改,你可以在以后的代码中重用,在给出代码之前,有一些有用的提示是有帮助的,

  1. 必须注意,数据框具有可用于循环的属性,例如,属性 .columns 让具有列列表
  2. 同样在绘图时,我注意到直接使用网格上的坐标不会让您的代码具有适应性,因此您需要“展平”您的网格坐标,因此使用ax.ravel()which 可以实现这一点。
  3. enumerate() 在循环访问对象的同时使第 i 个元素及其索引可用总是有用的。
  4. 一开始理解python中的子图很棘手,所以阅读其他人的代码真的很有帮助,我强烈建议你看一下scikit函数示例中的图(它有很大帮助)

这是我的代码建议:

fig, ax = plt.subplots(1, 3, sharex='col', sharey='row', figsize=(12,7))
ax = ax.ravel() 
# this method helps you to go from a 2x3 array coordinates to 
# 1x6 array, it will be helpful to use as below

for idx in range(3):
    ax[idx].hist(df.iloc[:,idx], bins=12, alpha=0.5)
    ax[idx].hist(df.iloc[:,idx+3], bins=12, alpha=0.5)
    ax[idx].set_title(df.columns[idx]+' with '+df.columns[idx+3])
    ax[idx].legend(loc='upper left')
Run Code Online (Sandbox Code Playgroud)

结果看起来像这样

我希望这是有帮助的,如果您需要更多详细信息,请随时问我问题:)

注意:重新使用亚历克斯的答案来编辑我的答案。另请查看此matplotlib 文档以获取更多详细信息。在这种特定情况下,第 3 点不再相关。


Ale*_*lex 6

我不知道我是否正确理解了您的问题,但类似的方法可以将这些图结合起来。您可能需要在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:])
Run Code Online (Sandbox Code Playgroud)

要将它们彼此相邻绘制,请尝试以下操作:

#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:])
Run Code Online (Sandbox Code Playgroud)

直方图,同一容器中的多个条形