matplotlib绘制多个2点线,没有连接起来

时间:2017-11-23 14:39:13

标签: python matplotlib plot

我想在散点图上打印一系列刻度,x和y点对存储在两个nx2数组中。它不是在点对之间的小刻度,而是在所有点之间打印线。我需要创建n行吗?

xs.round(2)
Out[212]: 
array([[ 555.59,  557.17],
       [ 867.64,  869.  ],
       [ 581.95,  583.25],
       [ 822.08,  823.47],
       [ 198.46,  199.91],
       [ 887.29,  888.84],
       [ 308.68,  310.06],
       [ 340.1 ,  341.52],
       [ 351.68,  353.21],
       [ 789.45,  790.89]])

ys.round(2)
Out[213]: 
array([[ 737.55,  738.78],
       [ 404.7 ,  406.17],
       [   7.17,    8.69],
       [ 276.72,  278.16],
       [  84.71,   86.1 ],
       [ 311.89,  313.14],
       [ 615.63,  617.08],
       [ 653.9 ,  655.32],
       [  76.33,   77.62],
       [ 858.54,  859.93]])
plt.plot(xs, ys)

enter image description here

2 个答案:

答案 0 :(得分:0)

您需要遍历数组xsys的终点:

import matplotlib.pyplot as plt
import numpy as np

xs = np.array([[ 555.59,  557.17],
       [ 867.64,  869.  ],
       [ 581.95,  583.25],
       [ 822.08,  823.47],
       [ 198.46,  199.91],
       [ 887.29,  888.84],
       [ 308.68,  310.06],
       [ 340.1 ,  341.52],
       [ 351.68,  353.21],
       [ 789.45,  790.89]])


ys = np.array([[ 737.55,  738.78],
       [ 404.7 ,  406.17],
       [   7.17,    8.69],
       [ 276.72,  278.16],
       [  84.71,   86.1 ],
       [ 311.89,  313.14],
       [ 615.63,  617.08],
       [ 653.9 ,  655.32],
       [  76.33,   77.62],
       [ 858.54,  859.93]])

for segment in zip(xs, ys):
    plt.plot(segment)

plt.show()

enter image description here

答案 1 :(得分:0)

最简单的解决方案是绘制n行。

import numpy as np
import matplotlib.pyplot as plt

xs  =np.array([[ 555.59,  557.17],
       [ 867.64,  869.  ],
       [ 581.95,  583.25],
       [ 822.08,  823.47],
       [ 198.46,  199.91],
       [ 887.29,  888.84],
       [ 308.68,  310.06],
       [ 340.1 ,  341.52],
       [ 351.68,  353.21],
       [ 789.45,  790.89]])

ys = np.array([[ 737.55,  738.78],
       [ 404.7 ,  406.17],
       [   7.17,    8.69],
       [ 276.72,  278.16],
       [  84.71,   86.1 ],
       [ 311.89,  313.14],
       [ 615.63,  617.08],
       [ 653.9 ,  655.32],
       [  76.33,   77.62],
       [ 858.54,  859.93]])

for (x,y) in zip(xs,ys):
    plt.plot(x,y, color="crimson")

plt.show()

enter image description here

如果n非常大,则更有效的解决方案是使用单个LineCollection来显示所有行。优点是可以更快地绘制,因为只使用一个集合而不是n线图。

# data as above.
seq = np.concatenate((xs[:,:,np.newaxis],ys[:,:,np.newaxis]), axis=2)
c= matplotlib.collections.LineCollection(seq)
plt.gca().add_collection(c)
plt.gca().autoscale()

plt.show()