Skip to content

Instantly share code, notes, and snippets.

@amankharwal
Created December 21, 2020 12:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amankharwal/1fadea63a9fce274d60186d816b67c36 to your computer and use it in GitHub Desktop.
Save amankharwal/1fadea63a9fce274d60186d816b67c36 to your computer and use it in GitHub Desktop.
from matplotlib.animation import FuncAnimation, FFMpegWriter
selected = racing_bar_filled.iloc[-1,:].sort_values(ascending=False)[:20].index
data = racing_bar_filled[selected].round()
fig,ax = plt.subplots(figsize=(9.3,7))
fig.subplots_adjust(left=0.18)
no_of_frames = data.shape[0] #Number of frames
#initiate the barplot with the first rows of the dataframe
bars = sns.barplot(y=data.columns,x=data.iloc[0,:],orient="h",ax=ax)
ax.set_xlim(0,1500)
txts = [ax.text(0,i,0,va="center") for i in range(data.shape[1])]
title_txt = ax.text(650,-1,"Date: ",fontsize=12)
ax.set_xlabel("Pay (Millions USD)")
ax.set_ylabel(None)
def animate(i):
# print(f"i={i}/{no_of_frames}")
#get i'th row of data
y = data.iloc[i,:]
#update title of the barplot axis
title_txt.set_text(f"Date: {str(data.index[i].date())}")
#update elements in both plots
for j, b, in enumerate(bars.patches):
#update each bar's height
b.set_width(y[j])
#update text for each bar (optional)
txts[j].set_text(f"${y[j].astype(int)}M")
txts[j].set_x(y[j])
anim=FuncAnimation(fig,animate,repeat=False,frames=no_of_frames,interval=1,blit=False)
anim.save('athletes.gif', writer='imagemagick', fps=120)
plt.close(fig)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment