我是 Python 的初学者。我正在尝试使用与 Z 轴相切的 matplotlib 绘制一个圆。我知道如何在 3D 中绘制球体,但不知道如何在 3D 绘图中绘制圆/环。有人可以帮我处理代码吗?提前致谢!
你需要通常的导入,加上 3D 工具包
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
您需要启用 3D
axes
对象
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
你需要一个圆,包含在平面中y-z
theta = np.linspace(0, 2 * np.pi, 201)
y = 10*np.cos(theta)
z = 10*np.sin(theta)
现在我们可以绘制原始圆,例如,一些围绕 z 轴旋转的圆,其中心也位于距 z 固定距离(等于圆的半径)处- 轴,以便它们与其相切
for i in range(18):
phi = i*np.pi/9
ax.plot(y*np.sin(phi)+10*np.sin(phi),
y*np.cos(phi)+10*np.cos(phi), z)
最终我们放置了一个垂直轴和一个图例
ax.plot((0,0),(0,0), (-10,10), '-k', label='z-axis')
ax.legend()
是时候看看我们得到了什么
plt.show()
mpl_toolkits.mplot3d.art3d
https://matplotlib.org/3.2.1/gallery/mplot3d/pathpatch3d.html被提及 在评论中,示例可以最小化为:
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
import mpl_toolkits.mplot3d.art3d as art3d
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Draw a circle on the x=0 'wall'
p = Circle((5, 5), 3)
ax.add_patch(p)
art3d.pathpatch_2d_to_3d(p, z=0, zdir="x")
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
ax.set_zlim(0, 10)
plt.show()
给出:
这比 https://stackoverflow.com/a/56871467/895245 好一点,因为它直接使用更高级别的
Circle
对象,而不是要求您显式绘制线条。
不幸的是,matplotlib 中的 3D 支持有点受限,如文档本身所述,您必须做一些额外的工作才能在不平行于主坐标平面的平面上绘图:How can matplotlib 2D patches be transformed to 3D with arbitrary法线?
在 matplotlib==3.2.2. 上测试
我不知道如何在 3D 绘图中画圆/环。我正在尝试绘制一个与 Z 轴相切的圆
你也可以
使用圆形补丁。这应该是最好的解决方案,但它在某些配置中效果不佳(例如,当图形具有
constrained
布局时会抛出错误)
使用具有单个 (x,y,z) 三元组的离散点,由一条线连接。只需设置一个坐标常量即可将一个平面圆投影到该轴上。这是当前选择的答案中使用的方法。
虽然后一种方法在智力上不是最优的,但它是解决
Circle
问题的可行方法。但是,在使用 Python 循环时,遍历所有单个点可能会很慢。这个答案中的变体加速并允许直接使用 numpy 数组操作而不是 Python 循环来编写更简洁的代码。
import numpy as np
import matplotlib.pyplot as plt
r = 2 # desired radius
n = 100 # number of points for the circle
x,y,z = 12, 56, 20 # circle center
# Get circle discrete points in z-plane
# Convert to Cartesian coordinates
# Set the 3rd coordinate to a fixed value
points = r*np.exp(1j*np.linspace(0, 2*np.pi, n))
u,v = np.real(points), np.imag(points)
w = np.repeat(r, n)
# Set pyplot configuration
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.set_aspect('equal')
# To plot one circle, just use:
#ax.plot (u+x,v+y,w+z)
# ---------------------------------------------
# # Fancy plot of circles at different locations
from itertools import permutations
perms = set(permutations([0,1,2])).union(permutations([0,1,3]))
coords = [u,v,w,-w]
for idx, idy, idz in perms: ax.plot(coords[idx]+x, coords[idy]+y, coords[idz]+z)