Matplotlib子图未对齐且首个子图不显示问题求助
解决Matplotlib子图不显示、无法并排对齐的问题
问题根源是你调用pandas的plot()方法时,没有指定要绘制到plt.subplot()创建的子图轴上。pandas的plot()默认会自动生成新的绘图窗口,导致和你手动创建的子图完全脱节,因此第一个子图无法显示,布局也错乱。
只需给pandas的plot()添加ax参数,指定对应的子图轴即可解决,修正后的完整代码如下:
# Plot of Total Number of Male and Female Athletes in each Year import matplotlib.pyplot as plt plt.figure(figsize=[20, 5]) # 创建第一个子图并保存轴对象 ax1 = plt.subplot(1, 2, 1) # 指定ax参数,将柱状图绑定到第一个子图 summer_gender_participants.plot(kind='bar', x='Year', y=['Male','Female'], edgecolor='Black', ax=ax1) plt.title("Summer Participant By Gender Count") plt.xlabel('Year') plt.ylabel('Number by Gender') # 创建第二个子图并保存轴对象 ax2 = plt.subplot(1, 2, 2) # 指定ax参数,将折线图绑定到第二个子图 winter_gender_participants.plot(kind='line', x='Year', y=['Male','Female'], ax=ax2) plt.title("Winter Participant By Gender Count") plt.xlabel('Year') plt.ylabel('Number by Gender') # 自动调整子图布局,避免标题、标签重叠 plt.tight_layout() plt.show()
核心要点:
- 通过
ax1 = plt.subplot(1,2,1)获取子图的轴对象,传递给pandasplot()的ax参数,让绘图内容绑定到指定子图 plt.tight_layout()可以自动优化子图间距,解决元素重叠问题,让布局更规整
内容的提问来源于stack exchange,提问作者Bashir
相关产品推荐
相关产品推荐

