使用 matplotlib 绘制多条线,仅使用 3 lists/arrays
Plot multiple lines with matplotlib, using only 3 lists/arrays
我想在 matplotlib 中以 3D 方式绘制 10 条线,但不必使用 ax.plot(x,y,z) 10 次。
这是我想出的荒谬代码 b/c 我无法想象 zip 和数组实际上是如何协同工作的。
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = np.array([0.,3.])
y = np.array([0.,0.])
z = np.array([0.,0.])
u = np.array([0.,3.])
v = np.array([.5,.5])
w = np.array([0.,0.])
a = np.array([0.,3.])
b = np.array([1.,1.])
c = np.array([0.,0.])
e = np.array([0.,3.])
d = np.array([1.5,1.5])
f = np.array([0.,0.])
r = np.array([0.,3.])
s = np.array([2.,2.])
t = np.array([0.,0.])
ax.set_xlabel("x axis")
ax.set_ylabel("y axis")
ax.set_zlabel("z axis")
ax.plot(x,y,z)
ax.plot(a,b,c)
ax.plot(r,s,t)
ax.plot(u,v,w)
ax.plot(e,d,f)
plt.show()
我猜我会使用 zip and/or for 循环。
谢谢,这是图。
您可以将所有数据点存储在一个大型数据数组中。这样你就可以遍历数组并做这样的事情:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# initialize array with size number of lines
data = np.full((2,3), None)
# fill data array with data points [x,y,z]
data[0] = [[0,3],[0,0],[0,0]]
data[1] = [[0,3],[0.5,0.5],[0,0]]
# etc...
# loop over data array and plot lines
for line in data:
ax.plot(line[0],line[1],line[2])
plt.show()
存储数据的方法有很多种,您也可以通过一次创建数组来跳过初始化步骤:
data = np.array([[[0,3],[0,0],[0,0]],
[[0,3],[0.5,0.5],[0,0]],
[[0,3],[0.5,0.5],[0,0]],
[...] ])
或使用 numpy.concatenate
等 numpy 函数向数据数组添加新行。
我想在 matplotlib 中以 3D 方式绘制 10 条线,但不必使用 ax.plot(x,y,z) 10 次。 这是我想出的荒谬代码 b/c 我无法想象 zip 和数组实际上是如何协同工作的。
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = np.array([0.,3.])
y = np.array([0.,0.])
z = np.array([0.,0.])
u = np.array([0.,3.])
v = np.array([.5,.5])
w = np.array([0.,0.])
a = np.array([0.,3.])
b = np.array([1.,1.])
c = np.array([0.,0.])
e = np.array([0.,3.])
d = np.array([1.5,1.5])
f = np.array([0.,0.])
r = np.array([0.,3.])
s = np.array([2.,2.])
t = np.array([0.,0.])
ax.set_xlabel("x axis")
ax.set_ylabel("y axis")
ax.set_zlabel("z axis")
ax.plot(x,y,z)
ax.plot(a,b,c)
ax.plot(r,s,t)
ax.plot(u,v,w)
ax.plot(e,d,f)
plt.show()
我猜我会使用 zip and/or for 循环。
谢谢,这是图。
您可以将所有数据点存储在一个大型数据数组中。这样你就可以遍历数组并做这样的事情:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# initialize array with size number of lines
data = np.full((2,3), None)
# fill data array with data points [x,y,z]
data[0] = [[0,3],[0,0],[0,0]]
data[1] = [[0,3],[0.5,0.5],[0,0]]
# etc...
# loop over data array and plot lines
for line in data:
ax.plot(line[0],line[1],line[2])
plt.show()
存储数据的方法有很多种,您也可以通过一次创建数组来跳过初始化步骤:
data = np.array([[[0,3],[0,0],[0,0]],
[[0,3],[0.5,0.5],[0,0]],
[[0,3],[0.5,0.5],[0,0]],
[...] ])
或使用 numpy.concatenate
等 numpy 函数向数据数组添加新行。