我有一个Pandas数据框架列表(示例):
df1 = pd.DataFrame({'Number':[-9,-8,0,1,2,3], 'A':[3,6,4,1,7,19], 'B':[2,4,4,0,7,1]})
df1.set_index('Number',inplace=True)
df2 = pd.DataFrame({'Number':[0,5,6,7,8,9], 'A':[8,7,3,5,2,15], 'B':[1,7,1,1,1,3]})
df2.set_index('Number',inplace=True)
df_list = [df1, df2] #In reality there are more than two in the list
我正在尝试使用Matplotlib绘制它们:
nrow = 2
ncol = 2
fig, axs = plt.subplots(nrow,ncol)
for i in range(nrow*ncol):
#Convert 1D to 2D
row = i / ncol
col = i % ncol
if i >= len(df_list):
axs[row,col].axis('off')
else:
df_list[i]['A'].plot(kind='bar',
ax=axs[row,col],
ylim=(0,20),
xlim=(-10,10),
figsize=(20,15),
color=('green'),
legend=False,
)
df_list[i]['B'].plot(kind='bar',
ax=axs[row,col],
ylim=(0,20),
xlim=(-10,10),
figsize=(20,15),
color=('yellow'),
legend=False,
)
生成的图表如下所示:
![enter image description here](https://istack.dev59.com/EAioA.webp)
更新:
感谢Ajean和JD Long在下面的回复中提供的代码,我现在正在使用这个Matplotlib代码:
df_list = [df1, df2]
nrow = 2
ncol = 2
fig, axs = plt.subplots(nrow,ncol,figsize=(20,15))
for i in range(nrow*ncol):
#Convert 1D to 2D
row = i / ncol
col = i % ncol
if i >= len(df_list):
axs[row,col].axis('off')
else:
axs[row,col].bar(np.array(df_list[i].index)-0.5, df_list[i]['A'], width=1, color='green')
axs[row,col].bar(np.array(df_list[i].index)-0.5, df_list[i]['B'], width=1, color='yellow')
axs[row,col].set_xlim([-10,10])
axs[row,col].set_ylim([0,20])
axs[row,col].xaxis.set_ticks(np.arange(-10, 11, 1))
这将产生所需的结果:
注意:每个条形图的宽度都设置为1.0,并且它们已经向左移动了-0.5,以使每个条形图位于刻度线中心。