如何在Python的matplotlib中将这两条3D线与曲面连接在一起

时间:2015-09-10 23:39:33

标签: python matplotlib 3d visualization scientific-computing

我有两个不同高度的轨道。我用3D绘制它们,但我希望将它们与表面连接在一起。到目前为止我有这张照片: enter image description here

我使用这个脚本:

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

font = {'size'   : 18}
matplotlib.rc('font', **font)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

#Read in data
data = np.genfromtxt('mu8.txt')
x, y = np.hsplit(data, 2)
N = len(x)
z = np.zeros(N)
z[:,] = 8.0

#Plot the first orbit
ax.plot(x, y, z, 'k-', linewidth=3.0)

#Read in data for second orbit
data = np.genfromtxt('mu9.txt')
x2, y2 = np.hsplit(data, 2)
N = len(x2)
z2 = np.zeros(N)
z2[:,] = 9.0

#Plot second orbit
ax.plot(x2, y2, z2, 'k-', linewidth=3.0)

#Join together the data for both orbits
xx = np.concatenate((x, x2), axis=0)
yy = np.concatenate((y, y2), axis=0)
zz = np.concatenate((z, z2), axis=0)

#Plot the surface
surf = ax.plot_surface(xx,yy,zz, color='m', alpha=0.3,
         linewidth=0)

#Set axis and things
ax.set_xticks([1.0,1.5,2])
ax.set_yticks([32,35,38])
ax.set_ylabel('$||u||_{2}$', fontsize=26, rotation=0, labelpad = 26)
ax.set_xlabel('$h$', fontsize=26)
ax.set_zlabel('$\mu$', fontsize=26, rotation=90)
plt.tight_layout()

plt.show()

如你所见 - 这看起来不太好。我想要这样做的动机是我需要绘制更多这些轨道,所有这些轨道都处于不同的高度。随着高度的变化,轨道变小。我认为最好的可视化方法是将它们与表面连接起来 - 这样,轨道就会找出一个变形的双管气缸,它会在最后收缩和夹紧。有没有办法做到这一点?

我希望能够以这种方式做一些事情: enter image description here

1 个答案:

答案 0 :(得分:2)

您想要找到连接第一个轨道中的第i个点到第二个轨道中的第i个点的线的等式。然后你可以使用i和z作为参数,改变所有可能的值来找到X和Y.

示例:

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
Z1 = 8.0
Z2 = 9.0
font = {'size'   : 18}
matplotlib.rc('font', **font)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

t = np.linspace(0, 2 * np.pi, 100)
x = np.cos(t)
y = np.sin(2 * t)
N = len(x)
z = np.zeros(N)
z[:,] = Z1

t = np.linspace(0, 2 * np.pi, 100)
x2 = 2 * np.cos(t)
y2 = 2 * np.sin(2*t)
N = len(x2)
z2 = np.zeros(N)
z2[:,] = Z2 

#Plot the first orbit
ax.plot(x, y, z, 'k-', linewidth=3.0)
#Plot second orbit
ax.plot(x2, y2, z2, 'k-', linewidth=3.0)


i, h = np.meshgrid(np.arange(len(x)), np.linspace(Z1, Z2, 10))
X = (x2[i] - x[i]) / (Z2 - Z1) * (h - Z1) + x[i]
Y = (y2[i] - y[i]) / (Z2 - Z1) * (h - Z1) + y[i]
surf = ax.plot_surface(X, Y, h, color='m', alpha=0.3,
         linewidth=0)


#Set axis and things
ax.set_xticks([1.0,1.5,2])
ax.set_yticks([32,35,38])
ax.set_ylabel('$||u||_{2}$', fontsize=26, rotation=0, labelpad = 26)
ax.set_xlabel('$h$', fontsize=26)
ax.set_zlabel('$\mu$', fontsize=26, rotation=90)
plt.tight_layout()

plt.show()

image of two orbits connected by a surface