【问题标题】:Plot several barplots using matplotlib and subplot使用 matplotlib 和 subplot 绘制多个条形图
【发布时间】:2019-06-24 08:02:25
【问题描述】:

我想使用 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 个正确的地块依次排列在一列中。 照片中显示了一个地块的示例。

感谢您的帮助和建议。

Figure Hereeee

【问题讨论】:

  • 您的代码是多余的。您可以通过plt.subplots 或 创建子图,您可以通过fig.add_subplot 添加子图。两者都不是。

标签: python matplotlib bar-chart subplot


【解决方案1】:

当您使用fig, axes = plt.subplots(figsize=(12, 8) , nrows = 3, ncols = 2) 创建图形时,您已经使用nrows 和ncols 关键字初始化了所有子图。 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)

【讨论】:

  • 帮助很大。另请参阅我发布的完整答案。
【解决方案2】:

感谢所有朋友的帮助。

最终生效的代码:

#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()

【讨论】:

    猜你喜欢
    • 2019-09-28
    • 2021-04-22
    • 2019-01-31
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多