为什么我的pyplot显示没有线?

时间:2015-02-01 22:44:54

标签: python matplotlib plot lines points

我是pyplot的新手,想知道我在这里做错了什么。

我想绘制一系列随机线段:

以下是一些示例代码:

import matplotlib.pyplot as plt

def testPlot():
  minx = miny = -1
  maxx = maxy = 30
  # some points randomly generated
  points = [((10, 21), (19, 22)), ((11, 9), (22, 27)), ((9, 13), (5, 9)), ((18, 4), (2, 21)), ((25, 27
  for pair in points:
    print pair
    for point in pair:  #plot each point with a small dot
      x = point[0]
      y = point[1]
      plt.plot(x,y,'bo')
    # draw a line between the pairs of points
    plt.plot(pair[0][0],pair[0][1],pair[1][0],pair[1][1],color='r',linewidth=2)
  plt.axis([minx,maxx,miny,maxy])
  plt.show()

这是我跑完之后得到的,点之间应该有线但是哪里有线?

((10, 21), (19, 22))
((11, 9), (22, 27))
((9, 13), (5, 9))
((18, 4), (2, 21))
((25, 27), (11, 13))

plotted points but no lines

感谢您提供任何线索

1 个答案:

答案 0 :(得分:2)

这就是问题所在:

...
plt.plot(pair[0][0],pair[0][1],pair[1][0],pair[1][1],color='r',linewidth=2)
...

您试图引用x,y,x1,y1,实际上应该是((x, x1), (y, y1))。纠正这个似乎工作正常:

def testPlot():
  minx = miny = -1
  maxx = maxy = 30
  # some points randomly generated
  points = [((10, 21), (19, 22)), ((11, 9), (22, 27)), ((9, 13), (5, 9)), ((18, 4), (2, 21)), ((25, 27), (11, 13))]
  for pair in points:
    print pair
    for point in pair:  #plot each point with a small dot
      x = point[0]
      y = point[1]
      plt.plot(x,y,'bo')
    # change this line to ((x, x1), (y, y1)) 
    plt.plot((pair[0][0],pair[1][0]),(pair[0][1],pair[1][1]), color='r',linewidth=2)
  plt.axis([minx,maxx,miny,maxy])
  plt.show()

结果:

enter image description here