gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:09:10 26 4
gpt4 key购买 nike

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

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com