CodingFrog
CodingFrog

Reputation: 1665

Animate matplotlib parametric example

What is the SIMPLIST way to animate the Python matlabplot parametric example?

I want to update the data within a loop item by item. Sadly this looks terrible, and is always flashing every colour of the rainbow! Is there a simple easy way that allows me to update data as it is calculated?

from mpl_toolkits.mplot3d import Axes3D  # noqa: F401 unused import

import numpy as np
import matplotlib.pyplot as plt
import math

plt.rcParams['legend.fontsize'] = 10

fig = plt.figure()
ax = fig.gca(projection='3d')
i = 10
theta = 0
x=[]
y=[]
z=[]
# Prepare arrays x, y, z
while (theta < 4*np.pi):
    theta += 0.05
    z += [i] 
    r = i**2 + 1
    x += [r * math.sin(theta)]
    y += [r * math.cos(theta)]
    i +=1

    ax.plot(x, y, z)    
    plt.pause(0.01)

Upvotes: 3

Views: 1674

Answers (1)

Jacques Kvam
Jacques Kvam

Reputation: 3076

Disclaimer, this uses a library I wrote called celluloid. There was some discussion about its merits in another answer. That being said here's basically your code with some celluloid lines sprinkled in:

import matplotlib
matplotlib.use('Agg')
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
import math
from celluloid import Camera

plt.rcParams['legend.fontsize'] = 10
fig = plt.figure()
ax = fig.gca(projection='3d')
camera = Camera(fig)
i = 10
x=[]
y=[]
z=[]
# Prepare arrays x, y, z
for theta in np.arange(0, 4*np.pi, 0.05):
    z += [i]
    r = i**2 + 1
    x += [r * math.sin(theta)]
    y += [r * math.cos(theta)]
    i +=1
    ax.plot(x, y, z, color='blue')
    camera.snap()
anim = camera.animate(blit=False, interval=10)
anim.save('3d.mp4')

Which can be turned into a gif like this:

enter image description here

Upvotes: 5

Related Questions