以有效的方式绘制具有相同X轴的多条线

时间:2019-01-04 14:02:31

标签: python-3.x numpy matplotlib

我有一个形状为(1360,1024)的numpy数组Y,其中包含聚合的1360数据集,每个数据集的长度为1024。我还有另一个形状(1024,)的数组,称为X。

这是Y [0:5]的样子(例如):

array([[13.72059917, 16.27633476, 18.49536324, ...,  0.81599081,
         0.99834043,  0.92653233],
       [13.42022991, 15.06573963, 17.45792198, ...,  0.85495144,
         0.75660354,  1.02977574],
       [13.6416111 , 16.03499603, 17.46924019, ...,  0.85070604,
         0.94057351,  0.87749392],
       [14.69120216, 16.85452461, 17.6070137 , ...,  0.86291492,
         0.99953759,  0.81989962],
       [13.57082653, 16.15143394, 17.55677032, ...,  0.93469822,
         0.96676576,  1.09142995]])

现在,我想将所有1360 Y数据集都绘制在彼此的顶部。对于它们所有的x轴都是相同的,即X。

我知道我可以这样做以绘制多件事情:

pyplot.plot(X,Y[0],X,Y[1],X,Y[2])

但这看起来像蛮力。也可以通过循环来解决,但不是很优雅。

我尝试使用列表理解来自动使X,Y [0] ...失败,但是失败了。

理想情况下,我想要一个单行解决方案且没有循环。

2 个答案:

答案 0 :(得分:1)

您可以为plot(x,y)提供2D阵列。如果x的长度为n,则y的形状必须为(n,m),才能绘制m行(每列一行)。

import numpy as np
import matplotlib.pyplot as plt

Y = np.random.rand(5,7)
X = np.arange(7)

plt.plot(X, Y.T)

plt.show()

对于许多列,这效率很低。生成此图的更有效方法是通过LineCollection

绘制一条“线”
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

Y = np.random.rand(5,7)
X = np.arange(7)

x = np.tile(X, Y.shape[0]).reshape(*Y.shape)
v = np.stack((x,Y), axis=-1)
c = LineCollection(v)

fig, ax = plt.subplots()
ax.add_collection(c)
ax.autoscale()
plt.show()

答案 1 :(得分:0)

plt.plot按列读取图。这是一个完整的示例:

import numpy as np
import matplotlib.pyplot as plt

xa = np.array([1, 2, 3])  # shape (3,)
xb = np.array([[1],
               [2],
               [3]])  # shape (3,1)
xc = np.array([[1, 4],
               [2, 5],
               [3, 6]])  # shape (3,2)

ya = np.array([[1, 4],
               [2, 5],
               [3, 6]])  # shape (3,2)
yb = np.array([1, 2, 3])  # shape (3,)

plt.figure()
plt.plot(xa, ya)  # res- 2 lines: ((1,1), (2,2), (3,3)) & ((1,4), (2,5), (3,6))

plt.figure()
plt.plot(xb, ya)  # res- 2 lines: ((1,1), (2,2), (3,3)) & ((1,4), (2,5), (3,6))

plt.figure()
plt.plot(xc, ya)  # res- 2 lines: ((1,1), (2,2), (3,3)) & ((4,4), (5,5), (6,6))

plt.figure()
plt.plot(xc.T, ya.T)  # res- 3 lines: ((1,1), (4,4)) & ((2,2),(5,5)) & ((3,3), (6,6))

plt.figure()
plt.plot(xa, yb)  # res- 1 line: ((1,1), (2,2), (3,3))

plt.figure()
plt.plot(xb, yb)  # res- 1 line: ((1,1), (2,2), (3,3))

plt.figure()
plt.plot(xc, yb)  # res- 2 lines: ((1,1), (2,2), (3,3)) & ((4,1), (5,2), (6,3))

plt.show()