简体   繁体   English

使用 matplotlib 和 subplot 绘制多个条形图

[英]Plot several barplots using matplotlib and subplot

I want to plot several barplots using matplotlib library (or other libraries if possible), and place each figure in its place using subplot.我想使用 matplotlib 库(或其他库,如果可能的话)绘制几个条形图,并使用 subplot 将每个图形放置在它的位置。

I am also using groupby to group by in each category and sum the values.我还使用 groupby 对每个类别进行分组并对值求和。 Then I just want to show three columns (Num1, Num2, Num3):然后我只想显示三列(Num1、Num2、Num3):

#Build subplot with three rows and two columns
fig, axes = plt.subplots(figsize=(12, 8) , nrows = 3, ncols = 2)
fig.tight_layout()

#five categorical columns and three numerical columns of interest
for i, category in enumerate(['Cat1', 'Cat2', 'Cat3', 'Cat4', 'Cat5']):   
    ax = fig.add_subplot(3,2,i+1)
    data.groupby(category).sum()[['Num1','Num2','Num3']].plot.bar(rot=0)
    plt.xticks(rotation = 90)

What I get are six empty plots arranged in 3rows and 2cols, followed by 5 correct plots arranged in one column one after another.我得到的是 6 个空图,它们排列在 3 行和 2 列中,然后是 5 个正确的图,一列接一列排列。 An example of a plots is seen in the photo.在照片中可以看到一个情节的例子。

Thanks for your helps and suggestions.感谢您的帮助和建议。

Figure Hereeee图这里

When you create a figure using fig, axes = plt.subplots(figsize=(12, 8) , nrows = 3, ncols = 2) , you already have initialized all of the subplots with the nrows and ncols keywords.当您使用fig, axes = plt.subplots(figsize=(12, 8) , nrows = 3, ncols = 2)创建图形时,您已经使用nrowsncols关键字初始化了所有子图。 axes is a list you can iterate over during the for loop. axes是一个列表,您可以在 for 循环期间迭代。

I think everything should work fine if you change:如果您更改,我认为一切都应该正常工作:

ax = fig.add_subplot(3,2,i+1)

to:到:

ax = axes[i]

All together:全部一起:

fig, axes = plt.subplots(figsize=(12, 8) , nrows = 3, ncols = 2)
fig.tight_layout()

#five categorical columns and three numerical columns of interest
for i, category in enumerate(['Cat1', 'Cat2', 'Cat3', 'Cat4', 'Cat5']):   
    ax = axes[i]
    data.groupby(category).sum()[['Num1','Num2','Num3']].plot.bar(rot=0,ax=ax)
    ax.xticks(rotation = 90)

Thanks for your helps all my friend.感谢您对我所有朋友的帮助。

The final code that worked:最终有效的代码:

#Build subplot with three rows and two columns
nrows = 3
ncols = 2
fig, axes = plt.subplots(figsize=(12, 16) , nrows = nrows, ncols = ncols)
fig.tight_layout()

#five categorical columns and three numerical columns of interest
for i, category in enumerate(['Cat1', 'Cat2', 'Cat3', 'Cat4', 'Cat5']):   
    ax = axes[i%nrows][i%ncols]
    data.groupby(category).sum()[['Num1','Num2','Num3']].plot.bar(rot=0, ax=ax)

#Rotating xticks for all
for ax in fig.axes:
    plt.sca(ax)
    plt.xticks(rotation=90)
    fig.tight_layout()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM