PlotLine中的Matlib垂直图例

2024-09-28 03:14:02 发布

您现在位置:Python中文网/ 问答频道 /正文

出于特定原因,我需要在matplotlib图例中显示一条垂直线。我想让matplotlib明白我想要一条直线.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)

enter image description here

我需要的是垂直线,而不是图例。有人能帮忙吗?在


Tags: fromimportmatplotlibasfig原因pltax
2条回答

在生成line2D对象时,可以使用垂直线标记。可以找到有效标记的列表here。在

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()

enter image description here

垂直标记所有行

如果目标是使图例中的每一行都垂直标记,而不是水平标记,则可以通过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()

enter image description here

微型复制线

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

^{pr2}$

enter image description here

相关问题 更多 >

    热门问题