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

Matplotlib绘制单画布双并列子图却输出两张独立画布问题求助

问题排查与解决方案

问题根源

代码在定义第二个子图的位置额外调用了plt.subplots()方法,该方法会直接生成一张全新的独立画布,因此原本需要放在同一张画布的第二个子图被输出到了新画布上,最终得到两张独立的绘图结果。

修正方法

删除plt.subplot(1,2,2)后的fig, ax = plt.subplots()语句,直接在当前子图上绘图即可,同时修正原代码中文本换行的语法问题,完整可运行的修正代码如下:

import matplotlib.pyplot as plt

# 绘制第一个子图
plt.subplot(1,2,1)
plt.hist(biib_neg_return_price, bins = 100, density = True, facecolor = "g")
plt.plot(x_fit, biib_normal_fit, color = "k", linestyle = "solid", linewidth = 1)
plt.xlabel("BIIB negative return price")
plt.ylabel("Frequency")
title_histo = "Histogram of BIIB Negative Return Price"
plt.title(title_histo)
# 三重引号包裹多行文本避免语法报错
plt.text(-0.4, 25, """skew = %0.2f
μ = %0.2f
σ = %0.2f""" % (biib_skew, biib_mu, biib_std))

# 绘制第二个子图
plt.subplot(1,2,2)
plt.plot(alpha_seq, VaR_history_biib_seq, color = "black", label = "Historical data")
plt.plot(alpha_seq, VaR_normal_biib_seq, color = "olive", label = "Fitted Normal Distribution")
plt.legend(loc = 0)
plt.xlabel("Level α")
plt.ylabel("Value at Risk")
title_VaR = "Value at Risk for BIIB"
plt.title(title_VaR)

# 可选:自动调整子图间距避免标签重叠
plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 05:54:00