[英]Replace Matplotlib legend's labels with image
我想在圖例中使用圖像而不是標簽。
例如,我畫了2行並顯示了一個圖例:
import matplotlib.pyplot as plt
plt.plot([1,2],label="first_image")
plt.plot([2,1],label="second_image")
plt.legend()
plot.show()
但我希望有這樣的東西:
請注意,這不是matplotlib圖例中插入圖像的重復,我的問題是“將標簽更改為圖像”,而另一個是“將圖例的符號更改為圖像”
在圖例中已經顯示了在圖例中創建圖像的概念( 在matplotlib圖例中插入圖像 ),其中圖像用作圖例條目的藝術家。
如果你想要一個線條句柄和圖例中的圖像,我們的想法是創建一個由兩個組合在一起的句柄,彼此相鄰。 唯一的問題是微調參數,使其看起來很吸引人。
import matplotlib.pyplot as plt
import matplotlib.lines
from matplotlib.transforms import Bbox, TransformedBbox
from matplotlib.legend_handler import HandlerBase
from matplotlib.image import BboxImage
class HandlerLineImage(HandlerBase):
def __init__(self, path, space=15, offset = 10 ):
self.space=space
self.offset=offset
self.image_data = plt.imread(path)
super(HandlerLineImage, self).__init__()
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize, trans):
l = matplotlib.lines.Line2D([xdescent+self.offset,xdescent+(width-self.space)/3.+self.offset],
[ydescent+height/2., ydescent+height/2.])
l.update_from(orig_handle)
l.set_clip_on(False)
l.set_transform(trans)
bb = Bbox.from_bounds(xdescent +(width+self.space)/3.+self.offset,
ydescent,
height*self.image_data.shape[1]/self.image_data.shape[0],
height)
tbb = TransformedBbox(bb, trans)
image = BboxImage(tbb)
image.set_data(self.image_data)
self.update_prop(image, orig_handle, legend)
return [l,image]
plt.figure(figsize=(4.8,3.2))
line, = plt.plot([1,2],[1.5,3], color="#1f66e0", lw=1.3)
line2, = plt.plot([1,2],[1,2], color="#efe400", lw=1.3)
plt.ylabel("Flower power")
plt.legend([line, line2], ["", ""],
handler_map={ line: HandlerLineImage("icon1.png"), line2: HandlerLineImage("icon2.png")},
handlelength=2, labelspacing=0.0, fontsize=36, borderpad=0.15, loc=2,
handletextpad=0.2, borderaxespad=0.15)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.