11

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!

ecjb
  • 3,699
  • 8
  • 24
  • 55
  • 1
    You need to use an interactive backend. By default Jupyter as well as the IPython console in Spyder use the inline backend, which basically shows a png image of the plot - png images are not interactive. – ImportanceOfBeingErnest Apr 23 '18 at 12:52
  • Many thanks @ImportanceOfBeingErnest. Do you have any materials (tutorial, website) about how do I do that exactly? – ecjb Apr 23 '18 at 12:56
  • Don't know about matplotlib but for interactive plotting I can recommend `pyqtgraph` which is using the Qt library for plotting and is lightningly fast. – Alfe Apr 23 '18 at 12:56
  • @ecjb Search for something like "interactive matplotlib jupyter" or so. – ImportanceOfBeingErnest Apr 23 '18 at 13:02
  • @ImportanceOfBeingErnest Oh yes it can. Have a look at https://youtu.be/vSbyDoXqAJI?t=4m32s . – Alfe Apr 23 '18 at 13:21

1 Answers1

15

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!

ecjb
  • 3,699
  • 8
  • 24
  • 55