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

如何设置GridSpec创建的Matplotlib子图的边框颜色?

解决Matplotlib GridSpec子图边框不显示的问题

问题根源

你的代码存在两个核心问题:

  1. 全局绘图接口误用:make_plot函数里使用plt.errorbar、plt.xlabel等全局pyplot方法,这些操作没有绑定到你创建的xtr_subplot子图对象上,导致子图边框(spines)未被正确初始化。
  2. 缩进错误:第一个for循环未缩进,会导致代码执行报错,无法正确生成子图内容。

修复后的完整代码

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

# 修改函数,接收子图Axes对象作为参数
def make_plot(ax, x, y, xerr, yerr, marker, mfc, legend, y_label):
    ax.errorbar(x, y, yerr=yerr, xerr=xerr, marker=marker,
                linestyle='none', alpha=.9, label=legend, mfc=mfc, capsize=3,
                ms=8, ecolor='black', elinewidth=0.7, capthick=0.5, mec='black', color='black')
    ax.set_xlabel(r'MgO (wt.%)', size=10, font='Arial')
    ax.set_ylabel(y_label, size=10, font='Arial')
    ax.tick_params(axis='both', which='major', labelsize=9)
    ax.tick_params(direction='in', which='minor', length=3, bottom=True, top=True, left=True, right=True)
    ax.tick_params(direction='in', right=True, top=True, left=True, bottom=True)
    ax.minorticks_on()
    ax.grid(False)
    # 强制显示子图四个边框并设置颜色
    for spine in ax.spines.values():
        spine.set_visible(True)
        spine.set_color('black')

# 示例数据(请替换为你的实际数据)
x = [1,2,3,4,5,6,7,8]
avg_si = [10,12,14,16,18,20,22,24]
avg_si_err = [0.5]*8
avg_Ca = [5,7,9,11,13,15,17,19]
avg_Ca_err = [0.3]*8
x_err = [0.2]*8
markers = ['o','s','^','v','D','p','*','h']
mfc = ['red','blue','green','orange','purple','brown','pink','gray']
legend = ['Sample '+str(i+1) for i in range(8)]
y_labels = ['SiO2 (wt.%)', 'Al2O3 (wt.%)', 'FeO (wt.%)', 'CaO (wt.%)']

# 创建画布与GridSpec布局
fig = plt.figure(1, figsize=(7, 7))
fig.set_facecolor('white')

gs = gridspec.GridSpec(4, 4)
gs.update(wspace=1.5, hspace=0.6)

# 第一个子图
xtr_subplot = fig.add_subplot(gs[0:2, 0:2])
xtr_subplot.set_facecolor('white')
for i in range(8):
    make_plot(xtr_subplot, x[i], avg_si[i], x_err[i], avg_si_err[i],
              markers[i], mfc[i], legend[i], y_labels[0])
xtr_subplot.legend()  # 可选:添加图例

# 第四个子图
xtr_subplot = fig.add_subplot(gs[2:4, 2:4])
xtr_subplot.set_facecolor('white')
for i in range(8):
    make_plot(xtr_subplot, x[i], avg_Ca[i], x_err[i], avg_Ca_err[i],
              markers[i], mfc[i], legend[i], y_labels[3])
xtr_subplot.legend()  # 可选:添加图例

plt.show()

关键修复点

  • 绑定子图对象:让make_plot接收ax参数,所有绘图和设置操作都基于目标子图,确保操作精准作用在指定子图上。
  • 显式控制边框:通过遍历ax.spines.values(),强制设置四个边框的可见性与颜色,覆盖Matplotlib默认样式的可能隐藏设置。
  • 修复缩进错误:修正for循环的缩进,保证循环内代码能正确执行。

内容的提问来源于stack exchange,提问作者O. Edward

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 02:35:38