Как добавить метку легенды в анимации Python

1

Я рисую данные (счет) из базы данных, использующей Matplotlib/Python. Я не могу понять, как иметь анимированную легенду. Я хочу, чтобы в легенде отображалось текущее значение строки.

Код:

def db_count():
    ### Connect to db and run query ...
    return count

x_data, y_data = [], []
figure = plt.figure()
count = db_count()
line, = plt.plot_date(x_data, y_data, '-', label=count)

def update(frame):
    x_data.append(datetime.now())
    count = db_count()
    y_data.append(count)
    line.set_data(x_data, y_data)
    figure.gca().autoscale_view()
    figure.gca().relim()
    return line,

animation = FuncAnimation(figure, update, interval=60000)

plt.xlabel('Time')
plt.ylabel('Counts')
plt.title('Total counts')
plt.legend(bbox_to_anchor=(1.05, 0.05))
plt.gcf().autofmt_xdate()
plt.xticks(rotation=45)
plt.show()

Спасибо

Теги:
matplotlib
animation
plot

1 ответ

3

Вам нужно установить метку вашей строки в функции update с помощью line.set_label(count), а затем вызвать plt.legend():

def db_count():
    ### Connect to db and run query ...
    return count

x_data, y_data = [], []
figure = plt.figure()
count = db_count()
line, = plt.plot_date(x_data, y_data, '-', label=count)

def update(frame):
    x_data.append(datetime.now())
    count = db_count()
    y_data.append(count)
    line.set_data(x_data, y_data)

    line.set_label(count) # set the label and draw the legend
    plt.legend(bbox_to_anchor=(1.05, 0.05))

    figure.gca().autoscale_view()
    figure.gca().relim()
    return line,

animation = FuncAnimation(figure, update, interval=60000)

plt.xlabel('Time')
plt.ylabel('Counts')
plt.title('Total counts')
plt.gcf().autofmt_xdate()
plt.xticks(rotation=45)
plt.show()

Ещё вопросы

Сообщество Overcoder
Наверх
Меню