如何在python动画中添加图例标签

如何在python动画中添加图例标签,python,animation,matplotlib,plot,Python,Animation,Matplotlib,Plot,我正在使用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, '-', la

我正在使用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()

谢谢

您需要使用
line在
update
函数中设置行的标签。设置标签(计数)
,然后调用
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()