如何在matplotlib

时间:2018-11-04 20:13:44

标签: python matplotlib

我试图通过循环数据在matplotlib中生成自定义图例处理程序。该处理程序包括图片和一行,如此处所说明(请参阅:Replace Matplotlib legend's labels with image)。我了解到handler_map始终会更新前一个处理程序,因此我在绘制线条后会生成它。 我的问题是,图例并没有停留在图例框中,而是其中的一部分在了框之外。 通过上面链接中描述的类,这段代码再现了错误:

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]

def plotting(x_axis, y_axis, fig, color, lineliste, handler_map, legendliste):
 picturepath = path
 ax = fig.add_subplot(111)
 line, =  plt.plot(x_axis,y_axis, c=color)
 lineliste.append(line)
 handler_map[line] = HandlerLineImage(picturepath)
 legendliste.append('')
 return fig, lineliste, handler_map, legendliste


def main():
 fig = plt.figure()
 list_plotting=[[0,1,3,5], [0,0.1,0.2,0.3], [1,5,9,12], [0,1,1,3], [5,5,4,3], [8,7,6,5,]]
 lineliste = []
 legendliste = []
 handler_map = dict()
 plt.xlabel('values')
 colors = iter(cm.nipy_spectral(np.linspace(0, 1, len(list_plotting))))
 cnt_style = 0
 cnt_element = 0
 for element in list_plotting:
  x_values=range(len(element))
  y_values=element
  fig, lineliste, handler_map, legendliste = plotting(x_values, y_values, fig, next(colors), lineliste, handler_map, legendliste)
 plt.legend(handles = lineliste, labels = legendliste, handler_map = handler_map, handlelength=4, labelspacing=0.0, fontsize=36, borderpad=0.1, handletextpad=0.2, borderaxespad=0.1, handleheight=2, loc='upper center', frameon = True, bbox_to_anchor=(1.35,1.1))
 fig.savefig("output.pdf", format='pdf', bbox_inches='tight')
 plt.close(fig)

if __name__=='__main__':
 main()

我本来以为anchored_bbox可以朝着正确的方向前进,但我无法弄清楚。与AnnotationBbox或我必须以某种方式定义BBoxBase的想法相同,我也无法弄清楚。由于我是python / matplotlib的新手,这似乎是一个异常/复杂的错误,如果有人可以提供帮助,我将非常高兴!

0 个答案:

没有答案