为什么在matplotlib中显示两行?

时间:2015-10-22 03:18:09

标签: python matplotlib graphing

我不明白为什么matplotlib正在创建另一条线?

import matplotlib.pyplot as plt

xy1 = []
x1 = 0


while x1 < 10:
    x1 = x1 + 1
    y1 = x1**2 
    xy1.append([x1,y1])


plt.plot(xy1)
print(xy1)
plt.show()

enter image description here

2 个答案:

答案 0 :(得分:2)

documentation,您可以看到plt.plot可以采用多个图表:

If x and/or y is 2-dimensional, then the corresponding columns will be plotted.

您的数据如下:

[[1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81], [10, 100]]

答案 1 :(得分:2)

正如@Hooked所说,因为xy1是2维的,而plot会将2维数组绘制为两列,而不是x和y列。

目前,您的列表如下:

In [14]: xy1
Out[14]: 
[[1, 1],
 [2, 4],
 [3, 9],
 [4, 16],
 [5, 25],
 [6, 36],
 [7, 49],
 [8, 64],
 [9, 81],
 [10, 100]]

要针对x绘制y,您需要将其解压缩到两个列表中。您可以使用zip*运算符执行此操作:

In [25]: xy2=zip(*xy1)

In [26]: xy2
Out[26]: [(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), (1, 4, 9, 16, 25, 36, 49, 64, 81, 100)]

然后您可以使用*运算符再次解压缩绘图:

In [28]: plt.plot(*xy2)
Out[28]: [<matplotlib.lines.Line2D at 0x10808c090>]

In [29]: plt.show()

enter image description here

或者,如果您将xy1变为numpy.array,则可以使用transpose功能:

In [48]: import numpy as np

In [49]: xy3=np.array(xy1)

In [50]: xy3
Out[50]: 
array([[  1,   1],
       [  2,   4],
       [  3,   9],
       [  4,  16],
       [  5,  25],
       [  6,  36],
       [  7,  49],
       [  8,  64],
       [  9,  81],
       [ 10, 100]])

In [51]: plt.plot(*xy3.transpose())
相关问题