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

如何在Matplotlib中为两条曲线之间添加填充图案?

在Matplotlib两条曲线间添加填充图案的解决方案

要在两条曲线间添加填充图案,首先需要处理两个数据集点数不一致的问题(data1有40个点,data2有33个点),通过插值将它们对齐到相同的y轴刻度,再使用fill_betweenx函数实现带图案的填充。以下是修改后的完整代码:

import numpy as np    
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.ticker as tck
from scipy.interpolate import interp1d


# 提取x、y数据
x1, y1 = data1[:, 0], data1[:, 1]
x2, y2 = data2[:, 0], data2[:, 1]

# 插值对齐y轴,确保两个数据集有相同的y值范围和点数
# 取两条曲线y的共同区间
y_min = max(y1.min(), y2.min())
y_max = min(y1.max(), y2.max())
# 生成统一的y序列
y_common = np.linspace(y_min, y_max, 1000)

# 插值得到对应y_common的x值
f1 = interp1d(y1, x1, kind='linear', fill_value="extrapolate")
f2 = interp1d(y2, x2, kind='linear', fill_value="extrapolate")
x1_common = f1(y_common)
x2_common = f2(y_common)

# 绘图设置
mpl.rcParams['text.latex.preamble'] = r'\usepackage{mathpazo}'
plt.rcParams['axes.linewidth'] = 2
plt.rc('text', usetex=True)
plt.rc('font', family='serif')

fig = plt.figure(figsize=(6,5))
fig.tight_layout()
plt.subplots_adjust(wspace=0.35)
ax = fig.add_subplot(111)
ax.tick_params(which='major',direction='in',width=2,length=10,top=True,right=True)
ax.tick_params(which='minor',direction='in',width=1,length=7,top=True,right=True)
    
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)

# 先绘制填充图案,放在曲线下方
ax.fill_betweenx(y_common, x1_common, x2_common, hatch='///', facecolor='none', edgecolor='gray', alpha=0.7)

# 绘制两条曲线
ax.plot(x1, y1, 'k-', linewidth=3.5)
ax.plot(x2, y2, 'k-', linewidth=3.5)

plt.ylabel(r'$y$',fontsize=22)
plt.xlabel(r'$x$',fontsize=22)

ax.set_xlim([-1,1])
ax.set_ylim([-1,1])

ax.xaxis.set_minor_locator(tck.AutoMinorLocator())
ax.yaxis.set_minor_locator(tck.AutoMinorLocator())

ax.set_xticks([-1.0,-0.50,0.0,0.50, 1.0])
ax.set_xticklabels([-1.0,-0.50,0.0,0.50, 1.0])
ax.set_yticks([-1.0,-0.50,0.0,0.50, 1.0])
ax.set_yticklabels([-1.0,-0.50,0.0,0.50, 1.0])

plt.show()

关键修改说明:

  • 使用scipy.interpolate.interp1d对两个数据集进行插值,生成统一的y轴序列对应的x值,解决点数不一致无法直接填充的问题
  • 调用fill_betweenx函数,通过hatch参数设置填充图案(可选值包括'/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'等),facecolor='none'只保留图案边框,避免遮挡曲线
  • 先绘制填充层,再绘制曲线,确保曲线在填充图案上方显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 07:57:13