Skip to content

Instantly share code, notes, and snippets.

@rishi93
Last active November 6, 2018 08:43
Show Gist options
  • Select an option

  • Save rishi93/9ae70b6715ab2d5d5dec2415ec2019c1 to your computer and use it in GitHub Desktop.

Select an option

Save rishi93/9ae70b6715ab2d5d5dec2415ec2019c1 to your computer and use it in GitHub Desktop.
Animated 2D plot in Matplotlib
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# Create the figure and the axes
fig = plt.figure()
ax = fig.add_subplot(111, title = 'Sine wave animation')
# Initialize the axes
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)
# Prepare the datapoints
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
bundled_data = [(x[i], y[i]) for i in range(0, 100)]
x_data, y_data = [], []
# Plot the data points
lines = ax.plot(x_data, y_data, animated = True)
# Setup the animation
def update(frame):
x_point, y_point = frame
x_data.append(x_point)
y_data.append(y_point)
lines[0].set_data(x_data, y_data)
return lines
animation = FuncAnimation(fig, update, frames = bundled_data, blit = True, interval = 40)
# Display the plot
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment