I want to update the legends in using the ArtistAnimation from Matplotlib.
I try to adapt this solution :
CodePudding user response:
This work for me :
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import animation
import numpy as np
a = np.random.rand(3,3)
fig, ax=plt.subplots()
container = []
colors = ["red","blue","green"]
labels = [0,1,2]
for i in range(a.shape[1]):
line, = ax.plot(a[:,i], color=colors[i])
title = ax.text(0.5,1.05,"Title {}".format(i),
size=plt.rcParams["axes.titlesize"],
ha="center", transform=ax.transAxes, )
testList = [] # Do an array of the color you want to see
for j in range(len(colors)): # For the example I added all the colors but you can pick only the ones you want
testList.append(mpl.patches.Patch(color=colors[j], label=labels[j]))
legend = ax.legend(handles=testList) # Create the legend
ax.add_artist(legend) # Add manually the legend
container.append([line, title])
ani = animation.ArtistAnimation(fig, container, interval=750, blit=False)
#ani.save('videos/test.gif')
plt.show()
Source :