2014-09-25 108 views
37

我想插入幾個小圖形(向量圖形,但可以根據需要製作柵格)到maplotlib圖的圖例中。圖例中每個項目會有一個圖形。在matplotlib圖例中插入圖像

我知道我可以使用something like an annotation box手動繪製整個圖例,但看起來很乏味,圖中的任何小小變化都需要手動修復。

pyplot.plot或更高版本pyplot.legend調用中調用或更高版本時是否有任何方法在標籤中包含圖形?

+2

只是爲了澄清,你想在*此外*圖形傳說字形或*代替*傳說字形? (也就是說,如果劇情中有紅線,你的傳說是否有紅線和自定義圖形,或者只是自定義圖形?) – Ajean 2014-09-25 05:04:22

+4

@askewchan [我認爲這是要走的路......](http:/ /matplotlib.org/users/legend_guide.html#implementing-a-custom-legend-handler) – 2014-09-25 10:03:01

+2

@Ajean,除了字形。圖例中的一行是:[[glyph] [label] [graphic]'。該圖顯示來自同一系統的兩個測量的數據;字形顯示了圖上標記的樣子,標籤命名測量,但圖形有助於解釋測量。 – askewchan 2014-09-25 12:47:50

回答

7

所以,下面是一個小黑客,但它可以讓你大部分的方式。注意:你需要用你想要的圖像替換[PATH TO IMAGE](否則你可以免費獲得Grace Hopper!)。您還可以通過傳遞參數image_stretch使圖像大於默認值。這是修復圖像長寬比的方法。如果您的圖像從一個系列重疊到下一個系列,請使用labelspacing參數。

import os 

from matplotlib.transforms import TransformedBbox 
from matplotlib.image import BboxImage 
from matplotlib.legend_handler import HandlerBase 
from matplotlib._png import read_png 

class ImageHandler(HandlerBase): 
    def create_artists(self, legend, orig_handle, 
         xdescent, ydescent, width, height, fontsize, 
         trans): 

     # enlarge the image by these margins 
     sx, sy = self.image_stretch 

     # create a bounding box to house the image 
     bb = Bbox.from_bounds(xdescent - sx, 
           ydescent - sy, 
           width + sx, 
           height + sy) 

     tbb = TransformedBbox(bb, trans) 
     image = BboxImage(tbb) 
     image.set_data(self.image_data) 

     self.update_prop(image, orig_handle, legend) 

     return [image] 

    def set_image(self, image_path, image_stretch=(0, 0)): 
     if not os.path.exists(image_path): 
      sample = get_sample_data("grace_hopper.png", asfileobj=False) 
      self.image_data = read_png(sample) 
     else: 
      self.image_data = read_png(image_path) 

     self.image_stretch = image_stretch 

# random data 
x = np.random.randn(100) 
y = np.random.randn(100) 
y2 = np.random.randn(100) 

# plot two series of scatter data 
s = plt.scatter(x, y, c='b') 
s2 = plt.scatter(x, y2, c='r') 

# setup the handler instance for the scattered data 
custom_handler = ImageHandler() 
custom_handler.set_image("[PATH TO IMAGE]", 
         image_stretch=(0, 20)) # this is for grace hopper 

# add the legend for the scattered data, mapping the 
# scattered points to the custom handler 
plt.legend([s, s2], 
      ['Scatters 1', 'Scatters 2'], 
      handler_map={s: custom_handler, s2: custom_handler}, 
      labelspacing=2, 
      frameon=False) 

下面是它產生:

grace hopper

+0

我剛剛回答了一個[關於如何用原始手柄以及圖像獲取圖例的類似問題](http:// stackoverflow。 com/questions/42155119/replace-matplotlib-legends-labels-with-image),以防有人需要。 – ImportanceOfBeingErnest 2017-02-10 22:49:27