matplotlib 带竖线的图例

vybvopom  于 2023-04-06  发布在  其他
关注(0)|答案(2)|浏览(223)

我需要在matplotlib图例中显示一条垂直线,因为有一个特定的原因。我试图让matplotlib理解我想要一条垂直线,其中包含lines.Line2D(x,y),但这显然不起作用。

  1. import matplotlib.pyplot as plt
  2. from matplotlib import lines
  3. fig, ax = plt.subplots()
  4. ax.plot([0,0],[0,3])
  5. lgd = []
  6. lgd.append(lines.Line2D([0,0],[0,1], color = 'blue', label = 'Vertical line'))
  7. plt.legend(handles = lgd)

我需要的线出现垂直,而不是传说。有人能帮忙吗?

3zwjbxry

3zwjbxry1#

你可以在制作line2D对象时使用垂直线标记。有效标记的列表可以在here中找到。

  1. import matplotlib.pyplot as plt
  2. from matplotlib import lines
  3. fig, ax = plt.subplots()
  4. ax.plot([0,0],[0,3])
  5. vertical_line = lines.Line2D([], [], color='#1f77b4', marker='|', linestyle='None',
  6. markersize=10, markeredgewidth=1.5, label='Vertical line')
  7. plt.legend(handles = [vertical_line])
  8. plt.show()

nhn9ugyo

nhn9ugyo2#

垂直标记所有行

如果目标是在图例中垂直标记每一行而不是水平标记每一行,则可以通过handler_map更新图例句柄。

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from matplotlib.legend_handler import HandlerLine2D
  4. plt.plot([1,3,2], label='something')
  5. plt.plot([.5,.5], [1,3], label='something else')
  6. def update_prop(handle, orig):
  7. handle.update_from(orig)
  8. x,y = handle.get_data()
  9. handle.set_data([np.mean(x)]*2, [0, 2*y[0]])
  10. plt.legend(handler_map={plt.Line2D:HandlerLine2D(update_func=update_prop)})
  11. plt.show()

以微缩形式复制行

如果目标是得到图例中绘制的线的缩小版本,原则上可以使用Using a miniature version of the plotted data as the legend handle的答案。需要稍微修改一下,以考虑可能的0宽度边界框,我现在也编辑到原始答案中。在这里,它看起来像:

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from matplotlib.legend_handler import HandlerLine2D
  4. import matplotlib.path as mpath
  5. from matplotlib.transforms import BboxTransformFrom, BboxTransformTo, Bbox
  6. class HandlerMiniatureLine(HandlerLine2D):
  7. def create_artists(self, legend, orig_handle,
  8. xdescent, ydescent, width, height, fontsize,
  9. trans):
  10. legline, _ = HandlerLine2D.create_artists(self,legend, orig_handle,
  11. xdescent, ydescent, width, height, fontsize, trans)
  12. legline.set_data(*orig_handle.get_data())
  13. ext = mpath.get_paths_extents([orig_handle.get_path()])
  14. if ext.width == 0:
  15. ext.x0 -= 0.1
  16. ext.x1 += 0.1
  17. bbox0 = BboxTransformFrom(ext)
  18. bbox1 = BboxTransformTo(Bbox.from_bounds(xdescent, ydescent, width, height))
  19. legline.set_transform(bbox0 + bbox1 + trans)
  20. return legline,
  21. plt.plot([1,3,2], label='something')
  22. plt.plot([.5,.5], [1,3], label='something else')
  23. plt.legend(handler_map={plt.Line2D:HandlerMiniatureLine()})
  24. plt.show()

展开查看全部

相关问题