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

Question:

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!

Asked By: ecjb

||

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!

Answered By: ecjb

You also mentioned spyder.
For Spyder users:
Tools –> Preferences –> IPython console,
select tab "Graphics" –> in Graphic backend, choose Automatic.
(based on Spyder 5.xx on Windows).

Answered By: tetukowski