绘制多条3D线:数据转换 [英] Plotting multiple 3D lines: data transformation

查看:98
本文介绍了绘制多条3D线:数据转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Python的3D图中绘制多条线.我的输入包含两个n x 3数组,即pos1和pos2,分别对应于两个3D点列表(行= x,y,z坐标).对于每个i,我都需要绘制一条线,将pos1中的第一个点连接到pos2中的第一个点.

I would like to plot multiple lines in a 3D plot in Python. My input consists of two n x 3 arrays, say pos1 and pos2, corresponding to two lists of 3D points (row = x,y,z coordinates). I need to plot a line connecting the ith point in pos1 to the ith point in pos2, for each i.

我有有效的代码,但是我确信这很糟糕,并且有更好的方法来实现.

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()

具体地说,我认为没有必要定义三个中间数组xvals, yvals, zvals.有没有更清洁的替代方法?例如,我应该将列表传递plot吗?

Specifically, I do not think it is necessary to define the three intermediate arrays xvals, yvals, zvals. Is there a cleaner alternative to this? Should I be passing a list to plot, for example?

推荐答案

我以前从未做过3D绘图,所以我不能说这是否是使用matplotlib必须提供的工具的最佳方法.但是您可以充分利用zip函数.

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. But you could make good use of the zip function.

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)

这篇关于绘制多条3D线:数据转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆