能否向matplotlib中的打印线添加数字?

2024-09-24 00:35:04 发布

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

我正在使用matplotlib.pyplot绘制不同的线。我可以添加一个带有标签的图例,通过颜色来区分哪一行是哪一行。不幸的是我是色盲。是否可以在每一行中写一个嵌入的数字?数字可能是这样的

enter image description here

然后可以识别每一行


Tags: matplotlib颜色绘制数字标签区分图例pyplot
2条回答

我的答案是基于this question

可以在matplotlib中使用latex数学符号。 由于$1$计为latex数学符号,因此可以将其用作标记

具有0,1,2的示例:

x, y, = np.arange(10), np.arange(10)

for a in range(3):

    plt.plot(x, a*y, alpha=0.5, marker='${}$'.format(a), markersize=10, label=a)

plt.legend()
plt.show()

enter image description here

编辑

在曲线上仅打印一次编号

x, y, = np.arange(10), np.arange(10)

colors = ['teal', 'darkslateblue', 'orange']

for a in range(3):

    plt.plot(x, a*y, c=colors[a])
    plt.plot(x[a+3], a*y[a+3], alpha=0.5, marker='${}$'.format(a), markersize=10, label=a, c=colors[a])

plt.legend()
plt.show()

enter image description here

有一个很好的小程序包matplotlib-label-lines实现了这一点(代码是github上的here

安装此软件包后,您的代码可能如下所示:

import numpy as np
import matplotlib.pyplot as plt
import labellines

x = np.linspace(0, 5, 100)

fig, ax = plt.subplots(1, 1)
ax.plot(x, x**2, linewidth=2, label="line example")
labellines.labelLines(ax.get_lines())

plt.show()

这会给你类似的东西

您还可以在图例中选择不同的线条样式,而不是颜色。 enter image description here

相关问题 更多 >