Vinica
Vinica

Reputation: 61

How to add legend label in python animation

I am plotting data (count) from database usling Matplotlib/Python. I cannot figure out how to have an animated legend. I want the legend to display the current value of the line.

The code is:

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

Thanks

Upvotes: 1

Views: 2911

Answers (1)

DavidG
DavidG

Reputation: 25371

You need to set the label of your line in the update function using line.set_label(count), then call 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()

Upvotes: 4

Related Questions