Creating Fireworks Animation in Python Using Matplotlib

Python, with its versatile libraries, is not only limited to data analysis and machine learning tasks. It can also be used to create beautiful animations, including fireworks displays. In this blog post, we’ll explore how to use the Matplotlib library to create a fireworks animation in Python.

First, let’s make sure we have the necessary libraries installed. We’ll be using Matplotlib for the animation and NumPy for numerical calculations. If you don’t have them installed, you can install them using pip:

bashpip install matplotlib numpy

Now, let’s dive into the code. We’ll create a class called Firework that will handle the generation and animation of a single firework. Each firework will consist of a set of particles that are randomly emitted from a central point.

pythonimport numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

class Firework:
def __init__(self, num_particles, colors, center=(0, 0), max_speed=10, max_lifetime=50):
self.particles = []
self.colors = colors
self.center = center
self.max_speed = max_speed
self.max_lifetime = max_lifetime

for _ in range(num_particles):
self.particles.append(self._generate_particle())

def _generate_particle(self):
# Randomly initialize particle properties
angle = np.random.uniform(0, 2 * np.pi)
speed = np.random.uniform(0.5, self.max_speed)
direction = np.array([np.cos(angle), np.sin(angle)]) * speed
lifetime = np.random.randint(self.max_lifetime // 2, self.max_lifetime)
position = self.center + direction * np.random.uniform(0, 1)
return {'position': position, 'direction': direction, 'lifetime': lifetime, 'color': np.random.choice(self.colors)}

def animate(self, frame, ax):
# Clear the previous frame
ax.clear()

# Update particle positions and check for expiration
for particle in self.particles:
particle['position'] += particle['direction']
particle['lifetime'] -= 1
if particle['lifetime'] <= 0:
self.particles.remove(particle)

# Plot the particles
for particle in self.particles:
ax.scatter(particle['position'][0], particle['position'][1], color=particle['color'])

# Set the limits of the plot
ax.set_xlim(-10, 10)
ax.set_ylim(-10, 10)
ax.set_aspect('equal')

# Create a figure and an axes
fig, ax = plt.subplots()

# Define the colors and create a firework
colors = ['red', 'orange', 'yellow', 'white']
firework = Firework(num_particles=100, colors=colors, center=(0, 0), max_speed=5, max_lifetime=100)

# Create the animation
ani = FuncAnimation(fig, firework.animate, frames=200, interval=50, blit=True, repeat=False)

# Display the animation
plt.show()

In this code, we define a Firework class that initializes a set of particles with random properties. The animate method updates the particle positions over time and plots them using Matplotlib. We use FuncAnimation from the Matplotlib animation module to create the animation.

Each particle is represented by a dictionary that contains its position, direction, lifetime, and color. The particles are randomly emitted from the center with a random direction and speed. Over time, the particles move according to their direction and speed, and their lifetime is reduced. When a particle’s lifetime reaches zero, it is removed from the animation.

You can adjust the parameters of the Firework class, such as the number of particles, colors, center position, maximum speed, and maximum lifetime, to create different effects.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *