Skip to content

01

Initialization

from matplotlib import pyplot as plt
%matplotlib inline
import matplotlib_inline
matplotlib_inline.backend_inline.set_matplotlib_formats('svg')
plt.figure(figsize=(16, 9), dpi=1920/16)
plt.figure(
  figsize=(6, 6),
  dpi=80
)

Example

df = df.sort_values(x).reset_index(drop=True)
plt.plot(
  df[x],
  df[y],
  'o'
)
plt.xlabel(x), plt.ylabel(y)

#add linear regression line to scatterplot
m, b = np.polyfit(df[x], df[y], 1)
plt.plot(df[x], m*df[x] + b)

plt.show()

Regression Line

m, b = np.polyfit(x, y, 1)
plt.plot(x, m*x + b)

Handrawn Style

with plt.xkcd():
    plt.show()

Animation

import numpy as np

import matplotlib.pyplot as plt
%matplotlib inline
import matplotlib_inline
matplotlib_inline.backend_inline.set_matplotlib_formats('svg')

from matplotlib.animation import FuncAnimation, writers, PillowWriter, FFMpegWriter

import seaborn as sns
sns.set_theme() ## affects all matplotlib and seaborn plots
plt.style.use('ggplot')
## hyperparameters
x_values = [1, 2, 3]
y_values = [1, 2, 3]
duration = 3 ## seconds
pause_duration = 2 ## seconds
res_w, res_h = 1920, 1080 ## video_resolution
aspect_w, aspect_h = (16, 9) ## aspect_ratio
## plot
actual_no_of_frames = len(y_values)
fig = plt.figure(
    figsize = (aspect_w, aspect_h), ## inches
    dpi = res_w/16 ## 
)
plt.tight_layout()
ax = plt.gca()  ## Get current axes
ax.set_title("Title")
ax.set_xlim(xmin=0, xmax=(len(y_values)-1)*1.05)
ax.set_ylim(ymin=0, ymax=max(y_values)*1.05)
ax.set_xticks(x_values, [""] + list(x_ticks))
ax.grid(False, axis="x")
line, = ax.plot(0, 0, linewidth=3)

def animation_frame(i):
  ## avoid changing axes, titles, etc in updates: low fps issue
  ## ax.set_title(y_values[i])
  if i not in [0, 1] and i <= actual_no_of_frames:
    ax.text(x=i-1, y=y_values[i-1], s=y_values[i-1], backgroundcolor="white", size=10, blit=True)
  line.set_xdata(x_values[:i])
  line.set_ydata(y_values[:i])

  return line, 

interval = (duration  * 1000)/actual_no_of_frames #ms
fps = 1000 / interval

no_of_blank_frames = int(fps * pause_duration)
total_no_of_frames = actual_no_of_frames + no_of_blank_frames

for _ in range(no_of_blank_frames):
  x_values.append(x_values[-1])
  y_values.append(y_values[-1])


## print(x_values)

animation = FuncAnimation(
  fig,
  func=animation_frame,
  frames=total_no_of_frames,
  interval=interval,
  blit=True ## comment if it causes issue
)

## setting up writer object
Writer = writers['ffmpeg'] ## PillowWriter
writer = Writer(
  fps=fps,
  bitrate=5000,
  metadata = dict(
    artist = 'Ahmed Thahir'
  )
)
animation.save('Line Graph Animation.gif', writer)
## animation.save('Line Graph Animation.mp4', writer)
Last Updated: 2024-05-12 ; Contributors: AhmedThahir

Comments