in Uncategorized

Animating Logit function plot in Matplotlib

Animation package in Matplotlib makes it very easy to animate plots. Here I will walk you through animating Logit fuction plot

Steps to make an animated chart is straight forward

  • Prepare data, for example, list X and list Y
  • Decide FPS(Frames Per Second) and Bitrate of animation and initialize an mp4 video writer using ffmpeg. This writer encodes the matplotlib figure to the video file at the set FPS rate.
  • Write a function that takes the frame number as the input. Matplotlib animation calls this function. Within the function draw the plot up to what is necessary for the given frame number. For example if there are 100 data points along X axis, and the total frames chosen are 50, then for frame f, draw for X from 0 to f*2. If the FPS chose is 25 and total number of frame chose in 50, The animation would last for 2 seconds.
  • Start and record animation by calling save function

Import libraries

[code lang=python]
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation

Calculate X values and Y values. In Logit, probability P of dependant variable is calculated as P=\frac{1}{1+e^{-(a+bX)}}

Take a=0 and b=1.0
Range of X , -10.0 to +10.0 at 0.1 increments
Calculate Y( or P)

[code lang=python]
Xmin = -10
Xmax = 10
X=np.arange(Xmin, Xmax, 0.02)
Y= np.fromiter(( (1/(1+np.exp(-xi))) for xi in X), X.dtype)

Initialize ffmpeg video writer with FPS and Bitrate

[code lang=python]
Writer = animation.writers['ffmpeg']
writer = Writer(fps=20, metadata=dict(artist='Me'), bitrate=1800)

Initialize figure and plot

[code lang=python]
%matplotlib notebook
fig = plt.figure(figsize=(10,6))
plt.xlim(np.min(X), np.max(X))
plt.ylim(np.min(Y), np.max(Y))
plt.title('Logit Func',fontsize=20)

Define animate function

[code lang=python]
def animate(i):
p = sns.lineplot(x=X[:i*5], y=Y[:i*5], color="r")

Launch animation and write video

[code lang=python]
ani = matplotlib.animation.FuncAnimation(fig, animate, frames=200, repeat=True)'Logit-basic.mp4', writer=writer)

Write a Comment