如何在matplotlib中用球体指向的箭头绘制球体

How to draw sphere with arrow pointing from sphere in matplotlib

我尝试使用 matplotlib 绘制一个球体来表示一个量子比特

import numpy as np 
import matplotlib.pyplot as plt
theta = [0, np.pi]
phi = [0, 2* np.pi]
N=100
theta_array = np.linspace(theta[0], theta[1], N)
phi_array = np.linspace(phi[0], phi[1], N)
theta_grid, phi_grid = np.meshgrid(theta_array,phi_array)

x = np.sin(theta_grid) * np.cos(phi_grid)
y = np.sin(theta_grid) * np.sin(phi_grid)
z = np.cos(theta_grid)

fig = plt.figure(figsize=(6,6))
ax = fig.gca(projection='3d')
ax.plot_surface(x, y, z, rstride=1, cstride=1, shade=False,linewidth=0)
plt.show()

我想在球体上添加方向与 xyz 轴平行的管状箭头,如下所示:

我不是 matplotlib 方面的专家,所以对我来说似乎很难。谁能帮我?提前致谢!

您可以使用 quiver 函数来实现您想要的。 请参阅下面的代码:

import numpy as np 
import matplotlib.pyplot as plt

theta = [0, np.pi]
phi = [0, 2* np.pi]
N=100
theta_array = np.linspace(theta[0], theta[1], N)
phi_array = np.linspace(phi[0], phi[1], N)
theta_grid, phi_grid = np.meshgrid(theta_array,phi_array)

x = np.sin(theta_grid) * np.cos(phi_grid)
y = np.sin(theta_grid) * np.sin(phi_grid)
z = np.cos(theta_grid)

fig = plt.figure(figsize=(6,6))
ax = fig.gca(projection='3d')
ax.view_init(azim=60)
ax.plot_surface(x, y, z, rstride=1, cstride=1, shade=False,linewidth=0)

#Set up arrows

ax.quiver(1,0,0,1,0,0,color = 'k', alpha = .8, lw = 3) #x arrow
ax.text(2.4,0,0,'Sx',fontsize=20) 

ax.quiver(0,1,0,0,1,0,color = 'k', alpha = .8, lw = 3)#y arrow
ax.text(0,2.4,0,'Sy',fontsize=20)

ax.quiver(0,0,1,0,0,1,color = 'k', alpha = .8, lw = 3)#z arrow
ax.text(-0.3,0,1.8,'Sz',fontsize=20)

plt.show()

输出结果为: