2017-02-10 8 views
2

凡例にラベルの代わりにイメージを使用したいと思います。Matplotlibの凡例のラベルを画像に置き換えてください。

たとえば、私は2線を描画し、伝説を示しています。

import matplotlib.pyplot as plt 
plt.plot([1,2],label="first_image") 
plt.plot([2,1],label="second_image") 
plt.legend() 
plot.show() 

What I have now

をしかし、私はこのような何かがしたい:このこと

The result I need

注意を複写されていないInsert image in matplotlib legend、 私の問題は「ラベルを画像に変更する」ですもう1つは「凡例のシンボルを画像に変更する」

+0

[matplotlibの伝説で画像を挿入](http://stackoverflow.com/questions/26029592/insert-image-in-matplotlib-legend) – Chuck

+1

未直接関係の可能性のある重複しますが、この例は正しい方向にあなたを導くかもしれません:http://matplotlib.org/examples/pylab_examples/demo_annotation_box.html – tom

答えて

2

凡例に画像を作成するコンセプトは、既にこの題目(Insert image in matplotlib legend)に示されています。ここで画像は凡例のアーティストとして使用されます。

凡例にラインハンドルとイメージが必要な場合は、両方のハンドルハンドルを作成してお互いに配置します。 唯一の問題は、これが魅力的に見えるようにパラメータを微調整することです。

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_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() 

enter image description here

+0

ありがとう!これは魅力的なように機能しています! – Drico

関連する問題