You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Matplotlib的plt.figure()实现多图横向排列?

问题描述

当前使用plt.figure()生成的图表是垂直排列的独立图窗,尝试使用plt.figure(nrows=1, ncols=2)时语法不合法,请问如何通过plt.figure()实现多图横向排列?

现有代码:

fig = plt.figure() #nrows=1, ncols=2)
ax = fig.add_subplot(111)
plt.scatter(x=res['actual'],y=res[0])
fig = plt.figure()
ax = fig.add_subplot(111)
plt.scatter(x=res['actual'],y=res[0])
res['diff']=res['actual']-res[0]
#plt.hist(res['diff'])

res['diff']=res['actual']-res[0]
plt.hist(res['diff'])

fig = plt.figure()
ax = fig.add_subplot(111)
plt.boxplot(res['diff'], showmeans=True)

fig = plt.figure() #nrows=1, ncols=2)
ax = fig.add_subplot(111)
plt.scatter(x=res['actual'],y=res[0])
fig = plt.figure()
ax = fig.add_subplot(111)
plt.scatter(x=res['actual'],y=res[0])
res['diff']=res['actual']-res[0]
#plt.hist(res['diff'])

res['diff']=res['actual']-res[0]
plt.hist(res['diff'])

fig = plt.figure()
ax = fig.add_subplot(111)
plt.boxplot(res['diff'], showmeans=True)
解决方案

plt.figure()本身不支持nrows和ncols参数,这两个参数属于plt.subplots()的专属用法。要通过plt.figure()实现多图横向排列,需先创建单个figure对象,再通过add_subplot()方法在该figure内划分横向布局的子图,具体实现如下:

核心逻辑

  1. 只创建一个plt.figure()对象,避免生成多个独立图窗
  2. 用add_subplot(行数, 列数, 子图索引)定义横向子图:比如1行2列的布局,子图索引依次为1、2
  3. 通过子图对象(如ax1、ax2)调用绘图方法,精准控制每个子图内容

代码示例(以1行2列布局为例)

# 创建单个figure,可指定尺寸适配横向布局
fig = plt.figure(figsize=(12, 5))

# 添加第一个子图(1行2列的第1个)
ax1 = fig.add_subplot(1, 2, 1)
ax1.scatter(x=res['actual'], y=res[0])
ax1.set_title('实际值vs预测值')
ax1.set_xlabel('实际值')
ax1.set_ylabel('预测值')

# 计算差值
res['diff'] = res['actual'] - res[0]

# 添加第二个子图(1行2列的第2个)
ax2 = fig.add_subplot(1, 2, 2)
ax2.hist(res['diff'])
ax2.set_title('差值分布直方图')
ax2.set_xlabel('差值')
ax2.set_ylabel('频数')

# 自动调整子图间距,避免元素重叠
plt.tight_layout()
plt.show()

扩展:1行3列布局(散点图+直方图+箱线图)

如果需要同时横向排列三类图表,只需扩展子图数量:

fig = plt.figure(figsize=(18, 5))

# 散点子图
ax1 = fig.add_subplot(1, 3, 1)
ax1.scatter(x=res['actual'], y=res[0])
ax1.set_title('实际值vs预测值')

# 直方图子图
ax2 = fig.add_subplot(1, 3, 2)
ax2.hist(res['diff'])
ax2.set_title('差值分布直方图')

# 箱线图子图
ax3 = fig.add_subplot(1, 3, 3)
ax3.boxplot(res['diff'], showmeans=True)
ax3.set_title('差值箱线图')

plt.tight_layout()
plt.show()

关键注意事项

  • 不要重复调用plt.figure(),否则会生成多个独立窗口,而非同一窗口内的子图
  • 优先使用子图对象的绘图方法(如ax1.scatter()),而非全局的plt.scatter(),避免绘图上下文混乱
  • plt.tight_layout()是优化布局的常用方法,可自动调整子图间距、标签位置

内容的提问来源于stack exchange,提问作者user2458922

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 18:11:01