使用多色线条将图例添加到matplotlib图中

时间:2018-03-11 18:44:20

标签: python matplotlib

关注the example on how to draw multicolored lines我可以根据某些颜色贴图绘制沿其长度改变颜色的线条。试图在图中添加图例我添加了以下代码:

plt.legend([lc], ["test"],\
    handler_map={lc: matplotlib.legend_handler.HandlerLineCollection()})

这会在图表中添加图例(如下图所示),但图例中图标的颜色与线条的颜色完全无关。这是尝试在此图中添加图例的错误方法,还是这是matplotlib的限制?

attempt at multicolored line with legend

1 个答案:

答案 0 :(得分:4)

这个想法也是在图例中显示一个线条集合。没有内置方法可以做到这一点,但可以将HandlerLineCollection子类化,并在其LineCollection方法中创建相应的create_artists

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLineCollection
from matplotlib.collections import LineCollection

class HandlerColorLineCollection(HandlerLineCollection):
    def create_artists(self, legend, artist ,xdescent, ydescent,
                        width, height, fontsize,trans):
        x = np.linspace(0,width,self.get_numpoints(legend)+1)
        y = np.zeros(self.get_numpoints(legend)+1)+height/2.-ydescent
        points = np.array([x, y]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)
        lc = LineCollection(segments, cmap=artist.cmap,
                     transform=trans)
        lc.set_array(x)
        lc.set_linewidth(artist.get_linewidth())
        return [lc]

t = np.linspace(0, 10, 200)
x = np.cos(np.pi * t)
y = np.sin(t)
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)

lc = LineCollection(segments, cmap=plt.get_cmap('copper'),
                    norm=plt.Normalize(0, 10), linewidth=3)
lc.set_array(t)

fig, ax = plt.subplots()
ax.add_collection(lc)

plt.legend([lc], ["test"],\
    handler_map={lc: HandlerColorLineCollection(numpoints=4)}, framealpha=1)

ax.autoscale_view()
plt.show()

enter image description here