![](/img/trans.png)
[英]Adding Vertical Line styles to a matplotlib legend to a plot made from a dataframe
[英]Adding a legend to a matplotlib plot with a multicolored line
按照有關如何繪制多色線條的示例,我可以根據一些顏色圖繪制沿其長度改變顏色的線條。 嘗試向情節添加圖例,我添加了以下代碼:
plt.legend([lc], ["test"],\
handler_map={lc: matplotlib.legend_handler.HandlerLineCollection()})
這為繪圖添加了一個圖例(下圖),但圖例中圖標的顏色與線條的顏色完全無關。 這是嘗試向該圖添加圖例的錯誤方法,還是 matplotlib 的限制?
這個想法也是在圖例中顯示一個線條集合。 沒有內置的方法可以做到這一點,但可以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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.