如何使用matplotlib沿着指定半径的点(x1,y1)和(x2,y2)的长度绘制圆柱体?

时间:2015-08-31 18:06:39

标签: python matplotlib

我想使用matplotlib沿着指定半径为r的点(x1,y1)和(x2,y2)的长度绘制圆柱体。请让我知道如何做到这一点。

1 个答案:

答案 0 :(得分:8)

为了好玩,我将把它推广到任何轴(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()

figure of 3d cylinder surface