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

如何指定Python/Matplotlib中重叠组合图例条目间的垂直间距

提问内容

目标

  • 在一张图中绘制两条曲线,以及对应的表示精度的填充区域,可参考最小工作示例(MWE)。
  • 遇到的问题:图例条目中的所有handler重叠,如何设置垂直间距避免虚线和实线互相重叠?
  • 期望输出:单个图例条目,包含红色和蓝色线条以及一个填充区域(蓝色或红色均可)。

期望输出效果

期望输出

说明

本问题是Stack Overflow同类问题的简化延伸版本。

测试代码

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.legend_handler import HandlerTuple

n = 11
x1 = np.linspace(0,1,n)
x2 = np.linspace(0,2,n)
y1 = x1 + 10
y2 = x2 + 5
y1err = 0.25 * np.ones(len(y1))
y2err = 0.50 * np.ones(len(y2))

handlers = []
labels = []

fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(111)

label1 = 'hello'
label2 = 'world'
p1, = ax.plot(x1,y1, linestyle='dotted', color='red')
f1 = ax.fill_between(x1,y1-y1err,y1+y1err, alpha=0.16, color='red')
p2, = ax.plot(x2,y2, linestyle='solid', color='blue')
f2 = ax.fill_between(x2,y2-y2err,y2+y2err, alpha=0.16, color='blue')

handlers.append((p1,f1,p2,f2))
labels.append((label1+'\n'+label2))
ax.legend(handlers,labels)
ax.grid()
ax.set_xlim(np.min(x2),np.max(x2))
plt.show()

当前输出效果

当前输出


解决方案

你只需要修改两处代码即可达到预期效果:

  1. 构造句柄列表时仅保留一个填充区域,删掉多余的填充句柄
  2. 调用legend时传入handler_map参数,通过HandlerTuple的pad参数调整图例元素的垂直间距,避免线条重叠

修改后的完整代码如下:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerTuple

n = 11
x1 = np.linspace(0,1,n)
x2 = np.linspace(0,2,n)
y1 = x1 + 10
y2 = x2 + 5
y1err = 0.25 * np.ones(len(y1))
y2err = 0.50 * np.ones(len(y2))

handlers = []
labels = []

fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(111)

label1 = 'hello'
label2 = 'world'
p1, = ax.plot(x1,y1, linestyle='dotted', color='red')
f1 = ax.fill_between(x1,y1-y1err,y1+y1err, alpha=0.16, color='red')
p2, = ax.plot(x2,y2, linestyle='solid', color='blue')
f2 = ax.fill_between(x2,y2-y2err,y2+y2err, alpha=0.16, color='blue')

# 仅保留一个填充区域的句柄
handlers.append((p1, p2, f1))
labels.append(label1+'\n'+label2)
# 设置HandlerTuple的垂直间距pad,避免元素重叠
ax.legend(handlers, labels, handler_map={tuple: HandlerTuple(ndivide=None, pad=1.2)})

ax.grid()
ax.set_xlim(np.min(x2),np.max(x2))
plt.show()

上述代码中pad参数可以根据实际显示效果调整数值,数值越大两个线条的垂直间距越大。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 20:48:01