keyboardP
keyboardP

Reputation: 69362

Plotting graph in python

I'm new to Python am trying to plot a graph based on the pyODE tutorial found here. I'm using pylab for the plotting. Below is the main part of the code and #added represents the code I've added in order to try and display the graph. When looking at the values themselves, y and v are the ones that change and x,z,u,w remain 0.000. When I run the program, the axis scale keeps scaling, implying that something is happening regarding the values, but no line is displayed. What am I doing wrong?

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

Upvotes: 2

Views: 3941

Answers (1)

unutbu
unutbu

Reputation: 879073

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.

Upvotes: 2

Related Questions