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

如何在Matplotlib中为子图间的空白区域填充颜色?

给Matplotlib子图间空白区域填充颜色的方法

下面提供两种实现方式,分别满足统一颜色和不同颜色的需求:

一、统一填充单一颜色

核心思路是在所有子图下方添加一个覆盖整个画布的底层轴,设置它的背景色,再让子图背景透明,这样底层颜色就会透过子图间隙显示出来。

代码示例:

import matplotlib.pyplot as plt

nb_vars = 4

# 创建4x4子图,设置间隙大小
fig, axs = plt.subplots(4,4,figsize=(8,8), gridspec_kw = {'wspace':0.20, 'hspace':0.20}, dpi=100)

# 添加底层轴,设置间隙颜色
bottom_ax = fig.add_subplot(111, frameon=True, facecolor="#e0f7fa")
# 隐藏底层轴的刻度
bottom_ax.set_xticks([])
bottom_ax.set_yticks([])

# 处理子图:隐藏刻度标签并设置背景透明
for row_ax in axs:
    for ax in row_ax:
        ax.set_yticklabels([])
        ax.set_xticklabels([])
        ax.patch.set_alpha(0)  # 让子图背景透明,露出底层颜色

plt.show()

二、为不同间隙填充不同颜色

如果需要给横向、纵向或者特定区域的间隙设置不同颜色,可以直接在画布上绘制对应间隙位置的矩形,通过控制矩形的坐标和尺寸来实现。

代码示例:

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

nb_vars = 4

# 创建子图并隐藏刻度标签
fig, axs = plt.subplots(4,4,figsize=(8,8), gridspec_kw = {'wspace':0.20, 'hspace':0.20}, dpi=100)
for row_ax in axs:
    for ax in row_ax:
        ax.set_yticklabels([])
        ax.set_xticklabels([])

# 获取子图的位置参数,计算间隙尺寸
first_ax_pos = axs[0,0].get_position()
ax_width = first_ax_pos.width
ax_height = first_ax_pos.height
wspace_size = 0.20 * ax_width  # 横向间隙的实际宽度
hspace_size = 0.20 * ax_height  # 纵向间隙的实际高度

# 绘制横向间隙的矩形(列与列之间)
for col in range(nb_vars - 1):
    x_start = first_ax_pos.x0 + (ax_width + wspace_size) * (col + 1)
    # 矩形覆盖所有行的横向间隙
    rect = Rectangle((x_start, first_ax_pos.y0), wspace_size, 
                     (ax_height + hspace_size)*nb_vars - hspace_size,
                     color="#ffccbc", zorder=-1)
    fig.patches.append(rect)

# 绘制纵向间隙的矩形(行与行之间)
for row in range(nb_vars - 1):
    y_start = first_ax_pos.y0 + (ax_height + hspace_size) * (row + 1)
    # 矩形覆盖所有列的纵向间隙
    rect = Rectangle((first_ax_pos.x0, y_start), 
                     (ax_width + wspace_size)*nb_vars - wspace_size, hspace_size,
                     color="#c8e6c9", zorder=-1)
    fig.patches.append(rect)

plt.show()

说明:

  • 第一种方法操作简单,适合所有间隙用同一种颜色的场景。
  • 第二种方法灵活性高,你可以根据需求修改矩形的位置、尺寸和颜色,实现特定间隙的个性化填色。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 16:07:32