python - Insert image in matplotlib legend -


i'd insert couple small graphics (vector graphics can made raster if necessary) legend of maplotlib plot. there 1 graphic per item in legend.

i know manually draw entire legend using something annotation box looks tedious, , small change in figure require fixing hand.

is there way include graphics in label in call pyplot.plot or later in pyplot.legend call?

so, below little hacky, can of way there. note: need replace [path image] image want (otherwise grace hopper free!). can make image larger default passing image_stretch parameter. hacky way fix aspect ratio on image. use labelspacing parameter if images overlap 1 series next.

import os  matplotlib.transforms import transformedbbox matplotlib.image import bboximage matplotlib.legend_handler import handlerbase matplotlib._png import read_png  class imagehandler(handlerbase):     def create_artists(self, legend, orig_handle,                        xdescent, ydescent, width, height, fontsize,                        trans):          # enlarge image these margins         sx, sy = self.image_stretch           # create bounding box house 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 2 series of scatter data s = plt.scatter(x, y, c='b') s2 = plt.scatter(x, y2, c='r')  # setup handler instance scattered data custom_handler = imagehandler() custom_handler.set_image("[path image]",                          image_stretch=(0, 20)) # grace hopper  # add legend scattered data, mapping # scattered points custom handler plt.legend([s, s2],            ['scatters 1', 'scatters 2'],            handler_map={s: custom_handler, s2: custom_handler},            labelspacing=2,            frameon=false) 

here's produces:

grace hopper


Comments

Popular posts from this blog

Python Kivy ListView: How to delete selected ListItemButton? -

ruby - How do I merge two hashes into a hash of arrays? -