简体   繁体   中英

Plotting 3D vector field with quiver3d() in Mayavi

I'm having a hard time to figure out why the following code isn't working inside the Jupyter Notebook! Any help is really appreciated

%gui qt
import matplotlib.pyplot as plt
import numpy as np
from sympy import symbols
from mayavi import mlab

x,y,z = symbols('x y z')
def gradient(f):
    return (f.diff(x), f.diff(y),f.diff(z))

f = x*y**2+z**2
g = gradient(f)

xrange = np.linspace(-3,3,15)
yrange = np.linspace(-3,3,15)
zrange = np.linspace(-3,3,15)
X,Y,Z = np.meshgrid(xrange, yrange, zrange)

U = np.zeros((15,15,15))
V = np.zeros((15,15,15))
W = np.zeros((15,15,15))

for i in range(len(xrange)):
    for j in range(len(yrange)):
        for k in range(len(zrange)):
            x1 = X[i,j,k]
            y1 = Y[i,j,k]
            z1 = Z[i,j,k]
            U[i,j,k] = g[0].subs({x:x1, y:y1, z:z1})
            V[i,j,k] = g[1].subs({x:x1, y:y1, z:z1})
            W[i,j,k] = g[2].subs({x:x1, y:y1, z:z1})


mlab.quiver3d(X,Y,Z,U,V,W)

In fact, I don't receive any error message just a black window of Mayavi. I have waited more than 10min but the windows permanents black. I'm running this code on a machine with Ubuntu 19.10. As a matter of completeness, I would like to mention that the below code works normally.

%gui qt
from mayavi import mlab
import numpy as np

def V(x, y, z):
    """ A 3D sinusoidal lattice with a parabolic confinement. """
    return np.cos(10*x) + np.cos(10*y) + np.cos(10*z) + 2*(x**2 + y**2 + z**2)
X, Y, Z = np.mgrid[-2:2:100j, -2:2:100j, -2:2:100j]
mlab.contour3d(X, Y, Z, V)

I could solve the problem by adding

mlab.init_notebook()
mlab.clf()

after importing the mlab module. In this way the plot appears inside Jupyter Notebook.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM