我认为这是一个非常有趣的问题。提供了解决问题所需的大部分信息在 matplotlib 的“图例指南”中。但是,我确实认为文档有点稀疏。
解决您问题的关键是创建一个新的“处理程序”,在尝试绘制艺术家的传奇时将调用该处理程序,并返回一个可以具有任何属性或形状的艺术家。在本例中,我们只需使用正确的数据创建一个新的 Line2D 对象即可绘制正弦波。
from matplotlib.legend_handler import HandlerLine2D
import matplotlib.pyplot as plt
class HandlerSinWave(HandlerLine2D):
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize,
trans):
xdata, y1 = orig_handle.get_data()
# scale the sin wave amplitude so that it fits neatly in the legend box
# first, rescale so that it is centered around 0 and have an amplitude of 1
min_val = np.min(y1)
max_val = np.max(y1)
y2 = (y1-(min_val+(max_val-min_val)/2))/((max_val-min_val)/2)
# then rescale based on the dimension of the box
y3 = height*y2 + xdescent+height/2
legline = matplotlib.lines.Line2D(xdata, y3)
self.update_prop(legline, orig_handle, legend)
legline.set_transform(trans)
return [legline]
fig, ax = plt.subplots()
x = np.arange(0,15,0.1)
y = np.sin(x)
sin1, = plt.plot(x,y, label='sine wave')
plt.legend(handler_map={sin1: HandlerSinWave()})
![enter image description here](https://i.stack.imgur.com/JqGVL.png)