1

I am trying to plot world population map using geopandas and matplotlib. I also use matplotlib animation to make graph animated for each year.

import matplotlib.ticker as ticker
import matplotlib.animation as animation
from IPython.display import HTML


fig,ax=plt.subplots(1,1,figsize=(15,5))

def animation_bar(year):
    filtered=df[df['Year']==year]  
    filtered.plot(ax=ax,column='Population',cmap='Reds',scheme='quantiles')
    ax.set_title(int(year),fontweight='bold')
    
animator=animation.FuncAnimation(fig,animation_bar,frames=sorted(df['Year'].unique()),interval=300)
HTML(animator.to_jshtml())

I get two graphs as an output: enter image description here

One graph is animated as intended, second one is static. One more concern about the output is that, the graph is smaller. As seen in the code I wanted the figsize=(15,5). It should be bigger than it is. I can't increase its size.

How to modify the code?

beridzeg45
  • 246
  • 2
  • 11

1 Answers1

0

You can use plt.close() anywhere in between plt.subplots and HTML(animator.to_jshtml()).

For example:

import matplotlib.pyplot as plt
import matplotlib.animation
from IPython.display import HTML

fig, ax = plt.subplots()
l = ax.plot([0, 2], [0, 3])[0]
t = [0, 1, 2]
x = [2, 0, 3]
animate = lambda n: l.set_data(t[:n+2], x[:n+2])
ani = matplotlib.animation.FuncAnimation(fig, animate, frames=2)

plt.close()  # here it is!
HTML(ani.to_jshtml())
Vladimir Fokow
  • 3,728
  • 2
  • 5
  • 27
  • But it'd be interesting to also know: 1) **Why** this solves the problem. 2) Why this problem happens in the first place. 3) And any other maybe more appropriate methods to solve it. – Vladimir Fokow Oct 26 '22 at 23:48