Search code examples
pythonmatplotlibdata-visualizationscatter-plotmatplotlib-animation

How to use matplotlib to animate bubble plot along with years


The following dataset needs to be animated with years as a bubble plot. With the year, Life Expectancy(X-Axis) and GDP(Y-Axis) need to be changed.

df.head()

enter image description here

Following Image for the Year of 1960 :

enter image description here

Following Image for Year 1961 :

enter image description here

My requirement is to animate Life-Expectancy vs GDP graph along with years. But when I tried to animate the graph using the below code, the result is not as expected.

fig, ax = plt.subplots()

s = ax.scatter([], [])

def animate_(i):

    # clear the axis each frame
    ax.clear()
    
    # replot things
    s = ax.scatter("LifeExpectency",
                   "GDP_in_log2",
                   alpha=0.5,
                   s='population',
                   c='colorForContinent',
                  data = df)
    return s,

anim = FuncAnimation(fig, animate_, frames = 62 , interval=500, blit=False)

#anim.save('Countries progression.mp4')

Following the image i got. It means all the year output merge one another. Any idea how to sort this out. enter image description here


Solution

  • You need to tie i in animate_ to the Year by filtering df

    try df[df['Year'] == some_function(i)]

    where some_function(i) maps the frame count to the year selected