gpt4 book ai didi

python - 使用 matplotlib 在图例中制作自定义垂直线标记

转载 作者:行者123 更新时间:2023-12-01 01:16:49 25 4
gpt4 key购买 nike

我有一个带有很多水平线的图形,每条水平线都有自己的标签。我还有一些带有标签的垂直线。默认情况下, pyplot.legend() 使用水平线标记显示这些标签,我想在视觉上区分垂直线标签和水平线标签。对于如何做到这一点有什么想法吗?下面是一个绘制线条的简单命令。

plt.axvline( x=10, linestyle='-',color='black',label='vertical line')
plt.legend()

enter image description here

另外:

我在以下位置了解到此建议 Legend with vertical line in matplotlib但我不确定如何为图例中的单个标签实现它。

最佳答案

这是针对多个垂直图例执行此操作的一种方法。我选择了非常简单的数据来提供可行的解决方案。您可以将概念扩展到您的实际数据

from matplotlib import lines

fig, ax = plt.subplots()

plt.plot([0, 5], [1, 1], label='y=1')
plt.plot([0, 5], [2, 2], label='y=2')
plt.plot([0, 5], [3, 3], label='y=3')

handles, _ = ax.get_legend_handles_labels()

vertical_pos = [5, 7, 10]
colors = ['r', 'g', 'b']

for x, c in zip(vertical_pos, colors):
plt.plot([x, x], [0, 3], color=c, label='Vertical x=%s' %x)

_, labels = ax.get_legend_handles_labels()

for c in colors:
vertical_line = lines.Line2D([], [], marker='|', linestyle='None', color=c,
markersize=10, markeredgewidth=1.5)
handles.append(vertical_line)

plt.legend(handles, labels)

编辑(使用axvline而不是plot)

for x, c in zip(vertical_pos, colors):
ax_ = plt.axvline( x=x, linestyle='-', color=c, label='Vertical x=%s' %x)

_, labels = ax.get_legend_handles_labels()

for c in colors:
vertical_line = lines.Line2D([], [], marker='|', linestyle='None', color=c,
markersize=10, markeredgewidth=1.5)
handles.append(vertical_line)

plt.legend(handles, labels)

enter image description here

关于python - 使用 matplotlib 在图例中制作自定义垂直线标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54272082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com