在matplotlib中使用垂直线的图例

Joa*_*lén 5 python matplotlib legend

出于特定原因,我需要在matplotlib图例中显示一条垂直线.我试图让matplotlib明白我想要一条带有lines.Line2D(x,y)的垂直线,但这显然不起作用.

import matplotlib.pyplot as plt
from matplotlib import lines
fig, ax = plt.subplots()
ax.plot([0,0],[0,3])
lgd = []
lgd.append(lines.Line2D([0,0],[0,1], color = 'blue', label = 'Vertical line'))
plt.legend(handles = lgd)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我需要显示垂直线,而不是图例.有人可以帮忙吗?

Imp*_*est 7

垂直标记所有线

如果目标是在图例中垂直而不是水平标记每一行,您可以通过handler_map.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLine2D

plt.plot([1,3,2], label='something')
plt.plot([.5,.5], [1,3], label='something else')

def update_prop(handle, orig):
    handle.update_from(orig)
    x,y = handle.get_data()
    handle.set_data([np.mean(x)]*2, [0, 2*y[0]])

plt.legend(handler_map={plt.Line2D:HandlerLine2D(update_func=update_prop)})

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

以微型形式复制线条

如果目标是获得图例中绘制线的微型版本,原则上您可以使用此答案“使用绘制数据的微型版本作为图例句柄”。不过,需要稍微修改一下才能解决可能为 0 宽度的边界框,我现在也将其编辑到原始答案中。在这里,它看起来像:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLine2D
import matplotlib.path as mpath
from matplotlib.transforms import BboxTransformFrom, BboxTransformTo, Bbox


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

        legline, _ = HandlerLine2D.create_artists(self,legend, orig_handle,
                                xdescent, ydescent, width, height, fontsize, trans)

        legline.set_data(*orig_handle.get_data())

        ext = mpath.get_paths_extents([orig_handle.get_path()])
        if ext.width == 0:
            ext.x0 -= 0.1
            ext.x1 += 0.1
        bbox0 = BboxTransformFrom(ext)
        bbox1 = BboxTransformTo(Bbox.from_bounds(xdescent, ydescent, width, height))

        legline.set_transform(bbox0 + bbox1 + trans)
        return legline,


plt.plot([1,3,2], label='something')
plt.plot([.5,.5], [1,3], label='something else')

plt.legend(handler_map={plt.Line2D:HandlerMiniatureLine()})

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Dav*_*idG 5

在创建line2D对象时,可以使用垂直线标记.可以在此处找到有效标记列表.

import matplotlib.pyplot as plt
from matplotlib import lines

fig, ax = plt.subplots()
ax.plot([0,0],[0,3])

vertical_line = lines.Line2D([], [], color='#1f77b4', marker='|', linestyle='None',
                          markersize=10, markeredgewidth=1.5, label='Vertical line')

plt.legend(handles = [vertical_line])

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述