简体   繁体   English

绘制多条3D线:数据转换

[英]Plotting multiple 3D lines: data transformation

I would like to plot multiple lines in a 3D plot in Python. 我想在Python的3D图中绘制多条线。 My input consists of two nx 3 arrays, say pos1 and pos2, corresponding to two lists of 3D points (row = x,y,z coordinates). 我的输入由两个NX 3阵列,说POS1和POS2,对应于3D点的两个列表(行= X,Y,Z坐标)。 I need to plot a line connecting the ith point in pos1 to the ith point in pos2, for each i. 我需要绘制在POS1第i个点连接到第i个点POS2一条线,每一个我。

I have working code, but I am certain that it is terrible and that there is a much better way to implement this. 我已经工作的代码,但我可以肯定,这是可怕的,并且有实现这个一个更好的方法。

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

# get plot set up
fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')

# minimal working example: two pairs.
pos1 = np.array([[0,0,0],[2,2,2]])
pos2 = np.array([[1,1,1],[3,3,3]])

xvals = np.transpose(np.array([pos1[:,0], pos2[:,0]]))
yvals = np.transpose(np.array([pos1[:,1], pos2[:,1]]))
zvals = np.transpose(([pos1[:,2], pos2[:,2]]))

N = len(pos1)

# call plot on each line
for i in range(N):
    ax.plot(xvals[i],yvals[i],zvals[i])

plt.show()

Specifically, I do not think it is necessary to define the three intermediate arrays xvals, yvals, zvals . 具体而言,我不认为这是必要的,以限定三个中间阵列xvals, yvals, zvals Is there a cleaner alternative to this? 有没有这样的清洁替代品? Should I be passing a list to plot , for example? 例如,我应该将列表传递plot吗?

I've never done 3D plotting before, so I can't say whether this would be the best method using the tools matplotlib has to offer. 我以前从未做过3D绘图,所以我不能说这是否是使用matplotlib必须提供的工具的最佳方法。 But you could make good use of the zip function. 但是您可以充分利用zip功能。

pos1 = np.array([[0,0,0],[2,2,2]])
pos2 = np.array([[1,1,1],[3,3,3]])

for point_pairs in zip(pos1, pos2):
    xs, ys, zs = zip(*point_pairs)
    ax.plot(xs, ys, zs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM