Animate a rotating 3D graph in matplotlib
If you want to learn more about matplotlib
animations you should really follow this tutorial. It explains in great length how to create animated plots.
Note: Creating animated plots require ffmpeg
or mencoder
to be installed.
Here is a version of his first example changed to work with your scatterplot.
# First import everthing you need
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
from mpl_toolkits.mplot3d import Axes3D
# Create some random data, I took this piece from here:
# http://matplotlib.org/mpl_examples/mplot3d/scatter3d_demo.py
def randrange(n, vmin, vmax):
return (vmax - vmin) * np.random.rand(n) + vmin
n = 100
xx = randrange(n, 23, 32)
yy = randrange(n, 0, 100)
zz = randrange(n, -50, -25)
# Create a figure and a 3D Axes
fig = plt.figure()
ax = Axes3D(fig)
# Create an init function and the animate functions.
# Both are explained in the tutorial. Since we are changing
# the the elevation and azimuth and no objects are really
# changed on the plot we don't have to return anything from
# the init and animate function. (return value is explained
# in the tutorial.
def init():
ax.scatter(xx, yy, zz, marker='o', s=20, c="goldenrod", alpha=0.6)
return fig,
def animate(i):
ax.view_init(elev=10., azim=i)
return fig,
# Animate
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=360, interval=20, blit=True)
# Save
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
How to rotate a 3d plot in python? (or as a animation) Rotate 3-D view using mouse
You need to define a function in order to get a specific animation. In your case it is a simple rotation:
def rotate(angle):
ax.view_init(azim=angle)
Then use the matplotlib animation:
rot_animation = animation.FuncAnimation(fig, rotate, frames=np.arange(0,362,2),interval=100)
This will call the rotate function with the frames
argument as angles and with an interval of 100ms
, so this will result in a rotation over 360°
with a 2°
step each 100ms
. To save the animation as a gif file:
rot_animation.save('path/rotation.gif', dpi=80, writer='imagemagick')
Jupyter | How to rotate 3D graph
To enable interactivity you need to use the notebook
backend of matplotlib. You can do this by running %matplotlib notebook
.
This must be done before you plot anything, e.g.:
%matplotlib notebook
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
fig = ...
Rotate interactively a 3D plot in python - matplotlib - Jupyter Notebook
Ok I found the answer on another post:
How can I open the interactive Matplotlib window in IPython notebook?.
the following line %matplotlib qt
has to be written at the beginning of the script + you have to restart the jupyter notebook and it works
Many thanks for your help guys!
Matplotlib Animation not rendering
I ran into a similar issue before, replacing "%matplotlib inline" with "%matplotlib notebook" in the given code solved it for me.
Animating a 3D vector with matplotlib
quiver
does not have an updating function, but you can easily remove an old quiver and plot a new one in each frame.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots(subplot_kw=dict(projection="3d"))
def get_arrow(theta):
x = np.cos(theta)
y = np.sin(theta)
z = 0
u = np.sin(2*theta)
v = np.sin(3*theta)
w = np.cos(3*theta)
return x,y,z,u,v,w
quiver = ax.quiver(*get_arrow(0))
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
ax.set_zlim(-2, 2)
def update(theta):
global quiver
quiver.remove()
quiver = ax.quiver(*get_arrow(theta))
ani = FuncAnimation(fig, update, frames=np.linspace(0,2*np.pi,200), interval=50)
plt.show()
Related Topics
How to Copy/Repeat an Array N Times into a New Array
Using Buttons in Tkinter to Navigate to Different Pages of the Application
Putting Multiple Conditions Using Np.Where on Python Pandas
Using Pyserial to Send Binary Data
Test a Function Called Twice in Python
How to Calculate a Gaussian Kernel Matrix Efficiently in Numpy
Print the Lines of a Log File Which Starts With Date Format "Yyyy-Mm-Dd" in Python
Write a Dictionary With Multiple Values to Store Data in Columns in the CSV File
Comparing Two Xml Files in Python
Unable to Install Psycopg2 (Pip Install Psycopg2)
How to Check Url Change With Selenium in Python
Write a Program That Find the Largest Integer in a String
Interactive Matplotlib Figures in Google Colab
Python - How to Fix "Valueerror: Not Enough Values to Unpack (Expected 2, Got 1)"
Replace Only Exactly Matching String Python Ndarry