Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate interactively a 3D plot in python - matplotlib - Jupyter Notebook

I was wondering how it is possible to interactively rotate a 3D plot as described in this video (if you decide from above or underneath or from right or left). I can generated a 3D plot in spyder or in a jupyter Notebook but after that it remains static and I cannot interact with it and rotate/change the angle of the viewpoint.

Here is the code:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

scale = 8
# Make data.
X = np.arange(-scale, scale, 0.25)
Y = np.arange(-scale, scale, 0.25)
X, Y = np.meshgrid(X, Y)
Z = X**2 + Y**2

# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
                   linewidth=0, antialiased=False)

# Customize the z axis.
ax.set_zlim(0, 100)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

# rotate the axes and update
for angle in range(0, 360):
   ax.view_init(30, 40)

# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()

Thank you very much in advance!

like image 418
ecjb Avatar asked Apr 23 '18 12:04

ecjb


People also ask

How do you rotate a 3D graph?

Rotating 3D GraphsTo rotate the 3D graph around the X axis press CTRL and drag. To rotate around the Y axis, press SHIFT and drag.


1 Answers

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!

like image 170
ecjb Avatar answered Sep 20 '22 07:09

ecjb