如何正确使用plt.subplots实现Matplotlib图表并排显示?
解决散点图并排展示的问题
你需要通过明确指定子图坐标轴对象实现两个图表并排,核心是先创建1行2列的子图布局,再将所有绘图操作绑定到对应坐标轴上,避免全局plt函数带来的混乱。以下是修改后的完整代码:
import matplotlib.pyplot as plt # 创建1行2列的子图布局,设置整体画布尺寸 fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(16, 7)) # ------------------- 第一个子图(ax1) ------------------- # 散点图:指定绘制到ax1 df_Baker.plot(kind='scatter', x='HS_GPA', y='Course_Grade', color='black', alpha=0.5, ax=ax1) df_Muriel.plot(kind='scatter', x='HS_GPA', y='Course_Grade', color='black', alpha=0.5, ax=ax1) df_Tanner.plot(kind='scatter', x='HS_GPA', y='Course_Grade', color='black', alpha=0.5, ax=ax1) # 回归线:绑定到ax1 ax1.plot(df_Baker.HS_GPA, Baker_fit[0] * df_Baker.HS_GPA + Baker_fit[1], color='darkblue', linewidth=2) ax1.plot(df_Tanner.HS_GPA, Tanner_fit[0] * df_Tanner.HS_GPA + Tanner_fit[1], color='deeppink', linewidth=2) ax1.plot(df_Muriel.HS_GPA, Muriel_fit[0] * df_Muriel.HS_GPA + Muriel_fit[1], color='deeppink', linewidth=2) # 设置子图1的图例、标题和坐标轴标签 ax1.legend(labels=['_h', '_hii', '_', '10 - 20','1 - 5'], title='Legend Test') ax1.set_title('BIO: Basic Concepts', size=24) ax1.set_xlabel('High school gpa', size=18) ax1.set_ylabel('Course Grade', size=18) # 修正原拼写错误cousre→Course # ------------------- 第二个子图(ax2) ------------------- # 散点图:指定绘制到ax2 df_Baker.plot(kind='scatter', x='HS_GPA', y='Course_Grade', color='black', alpha=0.5, ax=ax2) df_Muriel.plot(kind='scatter', x='HS_GPA', y='Course_Grade', color='black', alpha=0.5, ax=ax2) df_Tanner.plot(kind='scatter', x='HS_GPA', y='Course_Grade', color='black', alpha=0.5, ax=ax2) # 回归线:绑定到ax2 ax2.plot(df_Baker.HS_GPA, Baker_fit[0] * df_Baker.HS_GPA + Baker_fit[1], color='black', linewidth=2) ax2.plot(df_Tanner.HS_GPA, Tanner_fit[0] * df_Tanner.HS_GPA + Tanner_fit[1], color='black', linewidth=2) ax2.plot(df_Muriel.HS_GPA, Muriel_fit[0] * df_Muriel.HS_GPA + Muriel_fit[1], color='black', linewidth=2) # 设置子图2的图例、标题和坐标轴标签 ax2.legend(labels=['_h', '_hii', '_', '10 - 20','1 - 5'], title='Legend Test') ax2.set_title('BIO: Basic Concepts', size=24) ax2.set_xlabel('High school gpa', size=18) ax2.set_ylabel('Course Grade', size=18) # 修正原拼写错误 # 自动调整子图间距,避免标签重叠 plt.tight_layout() plt.show()
关键修改说明:
- 用
plt.subplots直接创建并排子图,获取ax1和ax2坐标轴对象,这是实现并排的核心 - 所有绘图操作(散点图、回归线)都通过
ax参数或ax.plot()绑定到对应子图,不再使用全局plt.plot() - 画布尺寸在
subplots中统一设置,避免每个plot重复设置引发冲突 - 使用
ax.set_title()、ax.set_xlabel()等方法替代全局plt.title(),确保设置作用到目标子图 - 添加
plt.tight_layout()自动调整间距,解决标签重叠问题
内容的提问来源于stack exchange,提问作者Aztec619
相关产品推荐
相关产品推荐

