Reputation: 25
I'm creating a trail of the (x,y) co-ordinates generated in a for-loop. But the plot pops up and it's blank. Can someone help the noob out?
import random
import math
import matplotlib.pyplot as pl
x = 0
y = 0
dx = 0
dy = 0
v = 2
n=100
pl.figure()
pl.hold(True)
for i in range(1,n):
dx = random.uniform(-2,2)
x = x+dx
y += ((v**2 - dx**2)**(0.5))*(random.randint(-1,1))
pl.plot(x,y)
print(x,y)
pl.show()
Upvotes: 0
Views: 69
Reputation: 375
The problem is that
pl.plot(x,y)
plots in the default style, which is to not plot the individual points, but just the lines between points. Since you are plotting one point at a time, nothing is appearing. You can either plot the points in such a way that they show up:
pl.plot(x,y,'ko')
This will mean that you do not see the sequence, but just the individual points. A better solution would be to keep track of the points and then plot them all at once:
import random
import math
import matplotlib.pyplot as plt
x = 0
y = 0
dx = 0
dy = 0
v = 2
n=100
plt.figure()
xs = []
ys = []
for i in range(1,n):
dx = random.uniform(-2,2)
x = x+dx
y += ((v**2 - dx**2)**(0.5))*(random.randint(-1,1))
xs.append(x)
ys.append(y)
plt.plot(xs,ys)
plt.show()
Note that you don't need plt.hold(True)
any more because you are only making one call to plt.plot()
Also note that I've changed pl
to plt
in the second example, since this is an extremely strong convention when using matplotlib
and it is a good idea to follow it, for code clarity.
Upvotes: 1
Reputation: 25518
You are trying to plot a line for each of your random points: the graph is blank because each single point isn't connected to any other. You could try building a list of the points and plotting that list as a line graph:
xarr, yarr = [], []
for i in range(1,n):
dx = random.uniform(-2,2)
x = x+dx
y += ((v**2 - dx**2)**(0.5))*(random.randint(-1,1))
xarr.append(x)
yarr.append(y)
pl.plot(xarr,yarr)
pl.show()
Upvotes: 2
Reputation: 18940
You need to specify a format string. Try to replace
pl.plot(x,y)
with
pl.plot(x,y,'r+')
or any other kind of format documented at http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot
Upvotes: 0