使用matplotlib fill_between填充区域时出现间隙问题求助
解决Matplotlib fill_between填充区域间隙问题
你使用Matplotlib的fill_between函数填充图表不同区域时出现间隙,开启interpolate=True又会导致填充形状变为非矩形。以下是你的代码:
import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() x = np.arange(0, 4 * np.pi, 0.01) y = np.sin(x) ax.plot(x, y, color='black') threshold = 0.75 ax.axhline(threshold, color='green', lw=2, alpha=0.7) ax.fill_between(x, 0, 1, where=y > threshold, facecolor=(0.5,0,0,0.5), ec=None,transform=ax.get_xaxis_transform()) ax.fill_between(x, 0, 1, where=y <= threshold, facecolor=(0,0.5,0,0.5), ec=None, transform=ax.get_xaxis_transform())
放大后的间隙效果如图:
问题原因
间隙出现是因为fill_between基于离散的x点判断where条件,当相邻x点的y值刚好在阈值两侧时,填充区域的边界无法完全衔接;而interpolate=True会让填充区域跟随曲线的插值点变化,导致形状不再是垂直矩形。
解决方案
改用ax.axvspan填充满足条件的垂直区间,能保证填充区域是完整矩形且无间隙。具体步骤是先识别出y > threshold的连续x区间,再逐个填充:
import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() x = np.arange(0, 4 * np.pi, 0.01) y = np.sin(x) ax.plot(x, y, color='black') threshold = 0.75 ax.axhline(threshold, color='green', lw=2, alpha=0.7) # 找出y > threshold的连续区间 mask = y > threshold # 定位区间起止索引 indices = np.where(np.diff(mask.astype(int)) != 0)[0] + 1 # 处理首尾边界情况 if mask[0]: indices = np.insert(indices, 0, 0) if mask[-1]: indices = np.append(indices, len(mask)) # 先填充绿色背景(y <= threshold的区域) ax.fill_between(x, 0, 1, facecolor=(0,0.5,0,0.5), ec=None, transform=ax.get_xaxis_transform()) # 逐个填充红色垂直区间(y > threshold的区域) for start_idx, end_idx in zip(indices[::2], indices[1::2]): x_start = x[start_idx] x_end = x[end_idx] ax.axvspan(x_start, x_end, ymin=0, ymax=1, facecolor=(0.5,0,0,0.5), ec=None, transform=ax.get_xaxis_transform()) plt.show()
说明
- 先识别连续的目标区间,避免离散点判断带来的间隙问题;
- 用
ax.axvspan填充垂直区域,确保形状为完整矩形; - 先填充背景色再叠加目标区间,逻辑更简洁,无需处理反向区间。
内容的提问来源于stack exchange,提问作者Joe Roberts
相关产品推荐
相关产品推荐

