matplotlib图不正确

时间:2015-03-10 23:41:03

标签: python matplotlib plot

我一直在尝试使用以下数据点集在matplotlib上制作一个简单的情节,但是我得到了一个完全令人困惑的错误情节。该图包括不在数据点集中的点。

enter image description here

我正在绘制的点集是:

[(0, 0), (3, 0), (0, 0), (2, 0), (0, 0), (3, 0), (1, 0), (7, 0), (2, 0), (0, 0), (5, 0), (2, 1), (10, 1), (1, 0), (1, 0), (8, 0), (3, 0), (1, 0), (2, 0), (2, 0), (1, 0), (6, 1), (3, 0), (3, 0), (12, 1), (3, 0), (0, 0), (2, 0), (0, 0), (2, 0), (3, 1), (0, 0), (4, 0), (4, 0), (2, 0), (2, 0)]

我只是打电话:

plt.plot(pts, 'ro')

我很想知道我在这里出错了。提前谢谢。

2 个答案:

答案 0 :(得分:0)

“点数集”让我觉得你想要一个散点图。如果你期待这样的事情:

Graph

然后你可能想要pyplot的scatter()函数。

import matplotlib.pyplot as plt

data = [(0, 0), (3, 0), (0, 0), (2, 0), (0, 0), (3, 0), (1, 0), (7, 0), (2, 0), (0, 0), (5, 0), (2, 1), (10, 1), (1, 0), (1, 0), (8, 0), (3, 0), (1, 0), (2, 0), (2, 0), (1, 0), (6, 1), (3, 0), (3, 0), (12, 1), (3, 0), (0, 0), (2, 0), (0, 0), (2, 0), (3, 1), (0, 0), (4, 0), (4, 0), (2, 0), (2, 0)]

x,y = zip(*data)

#plt.plot(data, 'ro')  # is the same as
#plt.plot(x, 'ro')     # this

plt.scatter(x, y)     # but i think you want scatter
plt.show()

对于plot()注意:

  

如果x和/或y是二维的,那么将绘制相应的列。

答案 1 :(得分:0)

目前,matplotlib认为您正在尝试将元组的每个条目与元组的索引进行对比。也就是说,你的情节有点(i,x_i)和(i,y_i),'i'从1到35。

正如@jedwards指出的那样,你可以使用分散函数。 或者,您可以通过提取元组的每个元素,使绘图函数显式绘制(x_i,y_i),如下所示:

import matplotlib.pyplot as plt

data = [(0, 0), (3, 0), (0, 0), (2, 0), (0, 0), (3, 0), (1, 0), (7, 0), (2, 0), (0, 0), (5, 0), (2, 1), (10, 1), (1, 0), (1, 0), (8, 0), (3, 0), (1, 0), (2, 0), (2, 0), (1, 0), (6, 1), (3, 0), (3, 0), (12, 1), (3, 0), (0, 0), (2, 0), (0, 0), (2, 0), (3, 1), (0, 0), (4, 0), (4, 0), (2, 0), (2, 0)]
plt.plot([int(i[0]) for i in data], [int(i[1]) for i in data], 'or')

plt.xlim(-1, 8) # Sets x-axis limits
plt.ylim(-1, 2) # Sets y-axis limits
plt.show()      # Show the plot