gpt4 book ai didi

python - 使用多色线向 matplotlib 图添加图例

转载 作者:太空宇宙 更新时间:2023-11-04 09:47:24 26 4
gpt4 key购买 nike

正在关注 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

最佳答案

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

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

关于python - 使用多色线向 matplotlib 图添加图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49223702/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com