使用枚举来标记图上的点,每个点都有不同的字母

Using enumerate to label points on a plot with a different letter for each point

我正在尝试用一个标签打印每个点,上面写着点 A/B/C/D(- 取决于它是哪个点)和每个点的坐标。 目前,所有的点都有相同的字母,但我希望它们在点上是独立的。我尝试了其他方法,但 none 奏效了。

no_points = 4
list_no_points = list(range(no_points))
xs = [1.0, 2.0, 3.0, 4.0]
ys = [1.0, 2.0, 3.0, 4.0]

plt.plot(xs, ys, linestyle = '--', marker = 'o', color = 'r')

for xy in zip(xs, ys):
    for x,i in enumerate(list_no_points):
        list_no_points[x] = string.ascii_uppercase[i]
    plt.annotate(f' Point ' + list_no_points[x] + ' (%.3f, %.3f)' % xy, xy=xy, textcoords='data')

plt.show()

这些点在您的代码中都具有相同的字母,因为 x 仅在内部 for 循环中发生变化。对于您的目的,内部 for 循环不是必需的。尝试类似的东西:

no_points = 4
list_no_points = list(range(65, 65 + no_points))
xs = [1.0, 2.0, 3.0, 4.0]
ys = [1.0, 2.0, 3.0, 4.0]

plt.plot(xs, ys, linestyle = '--', marker = 'o', color = 'r')

for i, xy in enumerate(zip(xs, ys)):
    plt.annotate(f' Point ' + chr(list_no_points[i]) + ' (%.3f, %.3f)' % xy, xy=xy, textcoords='data')

plt.show()

使用chr可以得到一个整数对应的ASCII字符('A'是65)

这是另一种可能性,但它避免使用枚举,而是让循环调整字符选择:

import matplotlib.pyplot as plt
import string

xs = [1.0, 2.0, 3.0, 4.0]
ys = [1.0, 2.0, 3.0, 4.0]

plt.plot(xs, ys, linestyle = '--', marker = 'o', color = 'r')

letter = 0
for xy in zip(xs, ys):
    plt.annotate(f' Point ' + string.ascii_uppercase[letter] + ' (%.3f, %.3f)' % xy, xy=xy, textcoords='data')
    letter += 1

plt.show()

以下应该可以解决问题:

import matplotlib.pyplot as plt
import string


if __name__ == '__main__':
    no_points = 4
    labels = [string.ascii_uppercase[i] for i in range(no_points)]

    xs = [1.0, 2.0, 3.0, 4.0]
    ys = [1.0, 2.0, 3.0, 4.0]

    fig, ax = plt.subplots()
    ax.plot(xs, ys, linestyle='--', marker='o', color='r')

    for count, label in enumerate(labels):
        ax.annotate(f"{label}({xs[count]}, {ys[count]})", xy=(xs[count], ys[count]))
    plt.show()

并且输出将符合预期:

你不需要第二个嵌套的for,你的字符串行可以直接插入到注解中:

import string
import matplotlib.pyplot as plt

no_points = 4
list_no_points = list(range(no_points))
xs = [1.0, 2.0, 3.0, 4.0]
ys = [1.0, 2.0, 3.0, 4.0]
plt.plot(xs, ys, linestyle = '--', marker = 'o', color = 'r')

for i, xy in enumerate(zip(xs, ys)):
    plt.annotate(f' Point ' + string.ascii_uppercase[i] + ' (%.3f, %.3f)' % xy, xy=xy, textcoords='data')

plt.show()