【发布时间】:2015-08-31 18:06:38
【问题描述】:
我想使用 matplotlib 沿点 (x1,y1) 和 (x2,y2) 的长度绘制一个具有指定半径 r 的圆柱体。请告诉我该怎么做。
【问题讨论】:
-
一个圆柱体只是堆叠的圆......你可以用
x,y=center_x+cos(angle)*radius,center_y+sin(angle)*radius计算圆边缘的点
标签: python matplotlib
我想使用 matplotlib 沿点 (x1,y1) 和 (x2,y2) 的长度绘制一个具有指定半径 r 的圆柱体。请告诉我该怎么做。
【问题讨论】:
x,y=center_x+cos(angle)*radius,center_y+sin(angle)*radius计算圆边缘的点
标签: python matplotlib
只是为了好玩,我将把它推广到任何轴 (x0, y0, z0) 到 (x1, y1, z1)。如果您想要 xy 平面中的轴,请将 z0 和 z1 设置为 0。
你可以很容易地找到轴的向量方程,方法是找到与轴相同方向的单位向量,然后将其添加到 p0 并沿轴的长度缩放它。通常你可以用 x = x0 + cos(theta) * R 和 y = y0 + sin(theta) * R 找到一个圆的坐标,但是这些圆不在 xy 平面上,所以我们需要制作我们自己的轴,其单位向量垂直于圆柱体的轴并相互垂直,然后从中获取 xyz 坐标。我使用这个网站来帮助我解决这个问题:http://mathforum.org/library/drmath/view/51734.html。代码如下:
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy.linalg import norm
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
origin = np.array([0, 0, 0])
#axis and radius
p0 = np.array([1, 3, 2])
p1 = np.array([8, 5, 9])
R = 5
#vector in direction of axis
v = p1 - p0
#find magnitude of vector
mag = norm(v)
#unit vector in direction of axis
v = v / mag
#make some vector not in the same direction as v
not_v = np.array([1, 0, 0])
if (v == not_v).all():
not_v = np.array([0, 1, 0])
#make vector perpendicular to v
n1 = np.cross(v, not_v)
#normalize n1
n1 /= norm(n1)
#make unit vector perpendicular to v and n1
n2 = np.cross(v, n1)
#surface ranges over t from 0 to length of axis and 0 to 2*pi
t = np.linspace(0, mag, 100)
theta = np.linspace(0, 2 * np.pi, 100)
#use meshgrid to make 2d arrays
t, theta = np.meshgrid(t, theta)
#generate coordinates for surface
X, Y, Z = [p0[i] + v[i] * t + R * np.sin(theta) * n1[i] + R * np.cos(theta) * n2[i] for i in [0, 1, 2]]
ax.plot_surface(X, Y, Z)
#plot axis
ax.plot(*zip(p0, p1), color = 'red')
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
ax.set_zlim(0, 10)
plt.show()
【讨论】:
R_at_position(xi),它可以离散任意子午线。 xi 是用于定义p0 和p1 的全局系统中的坐标。然后将 X、Y、Z 定义为X, Y, Z = [p0[i] + v[i] * t + [R_at_position(xi=x) for x in t[0]] * np.sin(theta) * n1[i] + [R_at_position(xi=x) for x in t[0]] * np.cos(theta) * n2[i] for i in [0, 1, 2]]。这将使函数能够绘制以p0 和p1 为导向的任何旋转曲面。