Matplotlib大子图下方出现多余小子图的原因排查
大子图下方出现小子图的原因及解决办法
问题根源
你代码开头用plt.subplots(2, n)创建了2行n列的子图,但后面又通过gridspec重新添加了新的轴元素。原来通过subplots创建的那些子图并没有被删除,所以会和后面添加的轴重叠,导致你看到大子图下方残留小子图。
另外,你同时使用了constrained_layout自动布局机制和plt.subplots_adjust()手动调整布局,这两个工具会互相干扰,容易引发布局混乱。
解决步骤
删除多余的子图创建代码
把开头的fig, axes = plt.subplots(2, n, figsize=(15, 7), layout='constrained')删掉,换成直接初始化画布:fig = plt.figure(figsize=(15, 7), layout='constrained')这样就不会提前创建多余的子图了。
避免布局机制冲突
删掉plt.subplots_adjust(right = 0.8, wspace=0.3, hspace=0.3)这一行,你已经用fig.set_constrained_layout_pads(...)设置了间距,足够满足布局需求,无需再用手动调整工具干扰自动布局。
修改后的完整代码示例
import matplotlib.pyplot as plt import numpy as np # 假设以下变量已提前定义 n = 3 standard_deviation_line = np.random.rand(10) lines = [np.random.rand(10) for _ in range(n)] parameter_text = "示例参数文本" # 初始化画布,不创建多余子图 fig = plt.figure(figsize=(15, 7), layout='constrained') spec = fig.add_gridspec(ncols=n, nrows=2) fig.set_size_inches(15, 10) fig.set_constrained_layout_pads(w_pad=0.8, h_pad=0.5, wspace=0, hspace=0) ax0 = fig.add_subplot(spec[0, :]) other_axes = [fig.add_subplot(spec[1, k]) for k in range(n)] ax1 = ax0.twinx() ax1.set_ylabel("Standard deviation") for i in range(n): matrix = np.random.rand(5, 5) other_axes[i].imshow(matrix, cmap='viridis', interpolation='nearest') other_axes[i].set_title(f'blah {i + 1}') ax0.set_xlabel("Episode number") ax0.set_ylabel("blah") ax1.plot(standard_deviation_line, label = "Title", linestyle='--', color='black') ax0.set_title("blah") for i in range(n): ax0.plot(lines[i], label=f"Blah") ax0.legend(loc='upper right', framealpha=1) ax1.legend(loc='upper left', framealpha=1) plt.figtext(0.97, 0.5, parameter_text, va='center', ha='right', fontsize=10) plt.show()
内容的提问来源于stack exchange,提问作者gournge
相关产品推荐
相关产品推荐

