Generate a MatPlotLib of a stickman walking (with stickman animations)
- User
Generate a MatPlotLib of a stickman walking (with stickman animations)
- Assistant
Creating a walking stickman animation using Matplotlib involves drawing the stickman and updating its limbs' positions over time to simulate walking. Below is a Python script that accomplishes this using Matplotlib's
FuncAnimation. The stickman's limbs (arms and legs) swing back and forth to mimic a walking motion.Prerequisites
Make sure you have
matplotlibinstalled. You can install it using pip if you haven't already:pip install matplotlibThe Code
import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation # Set up the figure and axis fig, ax = plt.subplots(figsize=(6, 8)) ax.set_xlim(-2, 2) ax.set_ylim(0, 12) ax.set_aspect('equal') ax.axis('off') # Turn off the axis # Initialize stickman parts body, = ax.plot([], [], 'k-', lw=2) # Body head, = ax.plot([], [], 'ko', markersize=12) # Head left_arm, = ax.plot([], [], 'k-', lw=2) # Left Arm right_arm, = ax.plot([], [], 'k-', lw=2) # Right Arm left_leg, = ax.plot([], [], 'k-', lw=2) # Left Leg right_leg, = ax.plot([], [], 'k-', lw=2) # Right Leg # Parameters for animation walking_cycle = 60 # Number of frames in a full walking cycle angle_amplitude = np.pi / 6 # Maximum swing angle (30 degrees) def init(): """Initialize the stickman parts.""" body.set_data([], []) head.set_data([], []) left_arm.set_data([], []) right_arm.set_data([], []) left_leg.set_data([], []) right_leg.set_data([], []) return body, head, left_arm, right_arm, left_leg, right_leg def animate(frame): """Update the stickman parts for each frame.""" # Calculate the phase of the walking cycle phase = (frame % walking_cycle) / walking_cycle * 2 * np.pi # Body position body_x = [0, 0] body_y = [6, 10] # Head position head_x = [0] head_y = [11] # Arms swing opposite to legs left_arm_angle = angle_amplitude * np.sin(phase) right_arm_angle = angle_amplitude * np.sin(phase + np.pi) # Legs swing left_leg_angle = angle_amplitude * np.sin(phase + np.pi) right_leg_angle = angle_amplitude * np.sin(phase) # Calculate arm positions arm_length = 3 left_arm_x = [0, arm_length * np.sin(left_arm_angle)] left_arm_y = [9, 9 - arm_length * np.cos(left_arm_angle)] right_arm_x = [0, arm_length * np.sin(right_arm_angle)] right_arm_y = [9, 9 - arm_length * np.cos(right_arm_angle)] # Calculate leg positions leg_length = 4 left_leg_x = [0, leg_length * np.sin(left_leg_angle)] left_leg_y = [6, 6 - leg_length * np.cos(left_leg_angle)] right_leg_x = [0, leg_length * np.sin(right_leg_angle)] right_leg_y = [6, 6 - leg_length * np.cos(right_leg_angle)] # Update the data for each part body.set_data(body_x, body_y) head.set_data(head_x, head_y) left_arm.set_data(left_arm_x, left_arm_y) right_arm.set_data(right_arm_x, right_arm_y) left_leg.set_data(left_leg_x, left_leg_y) right_leg.set_data(right_leg_x, right_leg_y) return body, head, left_arm, right_arm, left_leg, right_leg # Create the animation anim = FuncAnimation(fig, animate, init_func=init, frames=walking_cycle, interval=100, blit=True) # To display the animation in a Jupyter Notebook, uncomment the following lines: # from IPython.display import HTML # HTML(anim.to_jshtml()) # To save the animation as a GIF, uncomment the following line: # anim.save('walking_stickman.gif', writer='imagemagick') plt.show()How It Works
-
Initialization:
- A Matplotlib figure and axis are created with adjusted limits to accommodate the stickman's movement.
- The stickman's body parts (body, head, arms, and legs) are initialized as Matplotlib line objects.
-
Animation Function (
animate):- Calculates the current phase of the walking cycle based on the frame number.
- Determines the angles for the arms and legs using sine functions to create smooth swinging motions.
- Calculates the new positions of each limb based on these angles.
- Updates the line objects with the new positions.
-
Running the Animation:
FuncAnimationties everything together, repeatedly calling theanimatefunction to update the stickman's position.- The animation runs indefinitely, looping through the walking cycle.
Displaying or Saving the Animation
-
In a Jupyter Notebook:
- Uncomment the lines involving
HTML(anim.to_jshtml())to display the animation inline.
- Uncomment the lines involving
-
Saving as a GIF:
- Ensure you have ImageMagick installed.
- Uncomment the
anim.saveline to save the animation as a GIF file.
Customization
- Walking Cycle Speed: Adjust the
walking_cycleandintervalparameters to speed up or slow down the walking animation. - Swing Amplitude: Modify
angle_amplitudeto change how much the arms and legs swing. - Stickman Size: Change the lengths of arms and legs by modifying
arm_lengthandleg_length.
This script provides a simple yet effective walking stickman animation. You can further enhance it by adding more body details, background, or varying the walking speed dynamically.
-