Reputation: 2150
I've been trying to make a simple plot on matplotlib with the following set of datapoints, but I'm getting an incorrect plot which is utterly baffling. The plot includes points that aren't in the set of datapoints.
The set of points I'm plotting are:
[(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)]
And I'm simply calling:
plt.plot(pts, 'ro')
I'd love to know how I'm going wrong here. Thanks in advance.
Upvotes: 0
Views: 7075
Reputation:
Currently, matplotlib thinks that you're trying to plot each entry of the tuple against the index of the tuple. That is, your plot has the points (i, x_i) and (i, y_i) with 'i' going from 1 to 35.
As @jedwards pointed out, you could use the scatter function. Or, you could make the plot function explicitly plot (x_i, y_i) by extracting each element of the tuple as follows:
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
Upvotes: 1
Reputation: 30250
"Set of points" makes me think you want a scatter plot instead. If you're expecting something like this:
Then you probably want pyplot's scatter()
function.
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()
For plot()
note:
If x and/or y is 2-dimensional, then the corresponding columns will be plotted.
Upvotes: 0