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


谢谢

最佳答案

您需要使用updateline.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()

关于python - 如何在python动画中添加图例标签,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51999396/

10-12 17:48
查看更多