Tuesday, 31 August 2021

Saving an animated Matplotlib graph as a GIF file results in a different looking plot

I created an animated plot using FuncAnimation from the Matplotlib Animation class, and I want to save it as a .gif file. When I run the script, the output looks normal, and looks like this (the animation works fine):

enter image description here

However, when I try to save the animated plot as a .gif file using ImageMagick or PillowWriter, the plot looks like the following graph:

enter image description here

The lines are clearly much thicker, and in general, just looks very bad. The problem is attributed to the points (the purple, and red circles). Thus it seems like the plot is writing over each frame (which I think is the case). I can avoid this by just getting rid of them all together. But I don't want to do that as it would be hard to see the lines.

Here is the code:

line, = ax.plot([], [], color = 'blue', lw=1)
line2, = ax.plot([], [], color = 'red', lw=1)
line3, = ax.plot([], [], color = 'purple', lw=1)
def animate(i):
    line.set_data(x1[:i], y1[:i])
    line2.set_data(x2[:i], y2[:i])
    line3.set_data(x3[:i], y3[:i])
    point1, = ax.plot(x1[i], y1[i], marker='.', color='blue')
    point2, = ax.plot(x2[i], y2[i], marker='.', color='red')
    point3, = ax.plot(x3[i], y3[i], marker='.', color='purple')
    return line, line2, line3, point1, point2, point3,
        
ani = animation.FuncAnimation(fig, animate, interval=20, blit=True, repeat=False, frames=1000, save_count=1000)    
ani.save("TLI.gif", writer='imagemagick',fps=60)

The arrays x1, y1, x2, y2, x3, y3 are all 1D arrays that contain the x, y coordinates. So why is this happening? Why is it that the .gif file doesn't show what the plot shows when I run it directly? And also, how can I fix this?

I am also aware of this Stack Overflow question: matplotlib animation save is not obeying blit=True but it seems to work just fine in plt.show() which means the problem is definitely attributed to blitting. However, reading the answer of that question did not solve my problem because that only refers to ax.text opposed to a regular point plotted via ax.plot.



from Saving an animated Matplotlib graph as a GIF file results in a different looking plot

No comments:

Post a Comment