绘制3D矢量场

时间:2020-03-09 05:36:34

标签: python

我正在尝试绘制3D矢量场。我使用以下示例作为指导:

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np

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

x, y, z = np.meshgrid(np.arange(-0.8, 1, 0.2),
                      np.arange(-0.8, 1, 0.2),
                      np.arange(-0.8, 1, 0.8))

u = np.sin(np.pi * x) * np.cos(np.pi * y) * np.cos(np.pi * z)
v = -np.cos(np.pi * x) * np.sin(np.pi * y) * np.cos(np.pi * z)
w = (np.sqrt(2.0 / 3.0) * np.cos(np.pi * x) * np.cos(np.pi * y) *
     np.sin(np.pi * z))

ax.quiver(x, y, z, u, v, w, length=0.1)

plt.show()

该示例来自matplotlib示例library。但是,我想尝试一个不同的函数来替换u,v和w:

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np

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

x,y,z = np.meshgrid(np.arange(-0.1,0.005,0.1),np.arange(-0.1,0.005,0.1),np.arange(-0.1,0.005,0.1))
VolMag = 3.218E-6 #Volume of magnet in experiment in m^3
BR = np.sqrt(x**2 + y**2 + z**2)
MagMoment = np.array([0,0,(BInput*VolMag)/u0])
Bx = (u0/(4*np.pi))*(3*x*MagMoment*z)/BR**5
By = (u0/(4*np.pi))*(3*y*MagMoment*z)/BR**5
Bz = (u0/(4*np.pi))*((3*z*MagMoment*(z**2)/BR**5 - MagMoment/BR**3)

ax.quiver(x,y,z,Bx,By,Bz,length=0.1)
plt.show()

这给第16行带来了“无效语法”错误,这是为什么呢?我只更改了函数和定义的一些名称。

1 个答案:

答案 0 :(得分:1)

您似乎在此行上缺少右括号。

Bz = (u0/(4*np.pi))*((3*z*MagMoment*(z**2)/BR**5 - MagMoment/BR**3)

应该是

Bz = (u0/(4*np.pi))*((3*z*MagMoment*(z**2)/BR**5 - MagMoment/BR**3))