繁体   English   中英

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

[英]Plot several barplots using matplotlib and subplot

我想使用 matplotlib 库(或其他库,如果可能的话)绘制几个条形图,并使用 subplot 将每个图形放置在它的位置。

我还使用 groupby 对每个类别进行分组并对值求和。 然后我只想显示三列(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)

我得到的是 6 个空图,它们排列在 3 行和 2 列中,然后是 5 个正确的图,一列接一列排列。 在照片中可以看到一个情节的例子。

感谢您的帮助和建议。

图这里

当您使用fig, axes = plt.subplots(figsize=(12, 8) , nrows = 3, ncols = 2)创建图形时,您已经使用nrowsncols关键字初始化了所有子图。 axes是一个列表,您可以在 for 循环期间迭代。

如果您更改,我认为一切都应该正常工作:

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

到:

ax = axes[i]

全部一起:

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)

感谢您对我所有朋友的帮助。

最终有效的代码:

#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