在Python中绘图
我刚开始学习Python,想根据pyODE的教程画一个图,教程可以在这里找到。我使用的是pylab
来绘图。
下面是代码的主要部分,#added
表示我为了显示图形而添加的代码。看值的时候,y
和v
是会变化的,而x,z,u,w
一直保持在0.000
。当我运行程序时,坐标轴的刻度一直在变化,这说明值有在变化,但就是没有显示出任何线条。我到底哪里做错了呢?
谢谢
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
1 个回答
2
诀窍是先把你想要绘制的所有数值都收集起来,然后只需要调用一次 plot
函数。
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
在 plot
函数中,第三个参数 'r-'
是告诉 pylab
画一条红色的线,把 times
和 yvals
中的点连接起来。当你一个一个地绘制点时,pylab
无法知道要把这些点连接起来,因为每次绘制只包含一个点。每次为一个点调用 plot
函数也非常低效。