Использование enumerate для обозначения точек на графике разными буквами для каждой точки - PullRequest
1 голос
/ 27 мая 2020

Я пытаюсь напечатать каждую точку с этикеткой, на которой написано Point A / B / C / D (- в зависимости от того, какая это точка) и координаты каждой точки. На данный момент все точки имеют одну и ту же букву, но я бы хотел, чтобы они были индивидуальными по существу. Я пробовал другие способы, но ни один из них не помог.

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

Ответы [ 4 ]

0 голосов
/ 27 мая 2020

Вам не нужен второй вложенный для, и ваша строковая строка может быть вставлена ​​непосредственно в аннотацию:

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

enter image description here

0 голосов
/ 27 мая 2020

Вот еще одна возможность, но она избегает использования enumerate и позволяет l oop регулировать выбор символов:

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()
0 голосов
/ 27 мая 2020

Следующее должно помочь:

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

И результат будет таким, как ожидалось:

enter image description here

0 голосов
/ 27 мая 2020

Все точки имеют одну и ту же букву в вашем коде, потому что x изменяется только во внутреннем для l oop. Внутренний для l oop не нужен для вашей цели. Попробуйте что-то вроде:

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

Вы можете получить символ ASCII, соответствующий целому числу, используя chr ('A' равно 65)

...