keyboardP - 1 year ago 70

Python Question

I'm new to Python am trying to plot a graph based on the pyODE tutorial found here. I'm using

`pylab`

Below is the main part of the code and

`#added`

`y`

`v`

`x,z,u,w`

`0.000`

Thanks

`yplot = 0 #added`

#do the simulation

total_time = 0.0

dt = 0.04

while total_time<2.0:

x,y,z = body.getPosition()

u,v,w = body.getLinearVel()

print "%1.2fsec: pos=(%6.3f,%6.3f,%6.3f) vel=(%6.3f,%6.3f,%6.3f)" % \

(total_time, x,y,z,u,v,w)

world.step(dt)

total_time += dt

yplot += y #added

plot(total_time, yplot) #added

xlabel('Time') #added

ylabel('Height') #added

show() #added

Answer Source

The trick is to accumulate all the values you want to plot first, and then just call `plot`

once.

```
yplot = 0 #added
#do the simulation
total_time = 0.0
dt = 0.04
times=[]
yvals=[]
while total_time<2.0:
x,y,z = body.getPosition()
u,v,w = body.getLinearVel()
print "%1.2fsec: pos=(%6.3f,%6.3f,%6.3f) vel=(%6.3f,%6.3f,%6.3f)" % \
(total_time, x,y,z,u,v,w)
world.step(dt)
total_time += dt
yplot += y
times.append(total_time)
yvals.append(yplot)
plot(times, yvals,'r-')
xlabel('Time') #added
ylabel('Height') #added
show() #added
```

The third argument to plot, `'r-'`

, tells `pylab`

to draw a red line connecting the points listed in `times`

,`yvals`

. When you plot points one-at-a-time, there is no way to tell `pylab`

to connect the dots because each plot contains only a single point. Calling `plot`

for each point is also highly inefficient.