By using the widget mechanism of matplotlib, it is possible to create an interactive widget that is placed in Axes without depending on the GUI backend.
The following is an excerpt from widget documentation.
Widgets that are designed to work for any of the GUI backends. All of these widgets require you to predefine a matplotlib.axes.Axes instance and pass that as the first arg.
So, I will explain how to create a graph like the one above. In addition, I made the following on Jupyter Lab, but as I explained earlier, matplotlib.widget does not depend on GUI Backend, so the same result can be obtained not only on Jupyter notebook but also on Linux, Windows, Mac GUI. I think it will be. (I haven't tried it at hand)
First, import the required libraries. You also need to set the backend to widget.
%matplotlib widget
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.widgets import Slider
import numpy as np
Here, as an example, let's draw a graph of $ z = x ^ 2 + 2y ^ 2 $.
x = y = np.arange(-20, 20, 0.5)
X, Y = np.meshgrid(x, y)
Z = X*X + 2 * Y*Y
As you know, a figure is like a campus where you draw graphs with matplotlib. It is an image of putting Axes on the figure and plotting on it.
#Figure settings
fig = plt.figure(figsize=(5,5))
Next, create Axes on the figure.
#Added 3D graph and Axes for Slider in the figure
axcolor = 'gold'
gs = fig.add_gridspec(20, 20)
ax1 = fig.add_subplot(gs[:17,:], projection='3d')
ax_slider_z = fig.add_subplot(gs[18,:], facecolor=axcolor)
ax_slider_xy = fig.add_subplot(gs[19,:], facecolor=axcolor)
Next, create a Slider object. In the code below
I am doing.
#Slider settings
z0 = 0
xy0 = 0
delta = 10
slider_z = Slider(ax_slider_z, 'z-axis', -180, 180, valinit=z0, valstep=delta)
slider_xy = Slider(ax_slider_xy, 'xy-axis', -180, 180, valinit=xy0, valstep=delta)
Next, set the initial values of the visible angles around the z-axis and around the xy plane of the 3D graph. By changing this value, you can move the viewing angle of the 3D graph.
#Set the initial value of the viewing direction of the 3D graph
ax1.view_init(elev=z0, azim=xy0)
#Display 3D graph
ax1.plot_surface(X, Y, Z)
Next, create a callback function that will be called when you run Slider. Here, you can create a moving graph by specifying the viewing angle of the 3D graph and redrawing the graph.
#Callback function called when the Slider is moved
def view_change(val):
sz = slider_z.val
sxy = slider_xy.val
ax1.view_init(elev=sxy, azim=sz)
fig.canvas.draw_idle()
Finally, set the Slider object to the callback function you just created.
slider_z.on_changed(view_change)
slider_xy.on_changed(view_change)
plt.show()
Now you can easily create a graph that works on JupyterLab! I also put gist in here, so please use it if you like. (Same as the one explained above ...)
Recommended Posts