Matplotlib animation update legend using ArtistAnimation

Question:

I want to update the legends in using the ArtistAnimation from Matplotlib.

I try to adapt this solution : Matplotlib animation update title using ArtistAnimation to the legend but it didn’t worked. I tried a bunch of others things too but nothing seems to work.

In this case, I got no error, the result is just not what’s expected. The legend appears 1 time over 3, only for the green. And the result I want is that the legends change each time with the good color and label.

Here is a minimal example of what I’ve done :

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, )
    legend = ax.legend(handles=[mpl.patches.Patch(color=colors[i], label=labels[i])])
    container.append([line, title, legend])

ani = animation.ArtistAnimation(fig, container, interval=750, blit=False)
#ani.save('videos/test.gif')
plt.show()

Here is the result :
Result

Asked By: Pierre Marsaa

||

Answers:

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 :

Answered By: Madar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.