我想使用matplotlib库(或其他库,如果可能)绘制多个条形图,并使用子图将每个图形放在其位置。
我还使用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)
我得到的是在3行和2行中排列的六个空白图,然后在一个列中一个接一个地排列5个正确的图。 照片中显示了一个情节示例。
感谢您的帮助和建议。
答案 0 :(得分: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)
答案 1 :(得分:0)
感谢您对我所有朋友的帮助。
有效的最终代码:
#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()