In this blog, I will show you how to make a Spiral Animation in Python using Matplotlib and NumPy. Don’t worry if you are a beginner. I will explain step by step in very simple language.
Step 1: Install the required libraries
Before we start, you need Python to be installed and two Python libraries:
- NumPy → for handling numbers and arrays
- Matplotlib → for drawing and animation
Open your terminal or command prompt and type below code to install numpy and matplotlib.
pip install numpy matplotlib
If you are using VS Code, open the terminal inside it and run the same command.
Step 2: Create two files
We will use two Python files:
main.py
– this is the file where the animation will run.<strong>Animation.py</strong>
– this will store helper functions like making the line and figure.
main.py
import numpy as np
import matplotlib.pylab as plt
def initLine(ax):
# changed color from white → yellow
return ax.plot([], [], color='yellow', linewidth=1.5)[0]
def SpiralAnimation(frame, trace, z):
trace.set_data(np.real(z)[:frame], np.imag(z)[:frame])
return trace
def initFigureWindow():
fig, ax = plt.subplots(figsize=(5, 5))
fig.patch.set_facecolor('k') # black background
ax.patch.set_facecolor('k')
return fig, ax
Animation.py
import numpy as np
import matplotlib.pylab as plt
def initLine(ax):
return ax.plot([], [], color='yellow', linewidth=1.5)[0]
def SpiralAnimation(frame, trace, z):
trace.set_data(np.real(z)[:frame], np.imag(z)[:frame])
return trace
def initFigureWindow():
fig, ax = plt.subplots(figsize=(5, 5))
fig.patch.set_facecolor('k') # black background
ax.patch.set_facecolor('k')
return fig, ax
Output: Spiral Animation in Python using numpy and matplotlib
Step 5: Run the code
- Save both files in the same folder.
- Open terminal in that folder.
- Run:
python main.py
Final Words
That’s it! You just made your own spiral animation in Python. This is a fun project to start with if you are new to Python graphics. You can change numbers, colors, speed, and even save the animation as a video later.