在python中绘制图形 [英] Plotting graph in python
问题描述
我是 Python 新手,正在尝试根据 here<的 pyODE 教程绘制图形/a>.我正在使用 pylab
进行绘图.下面是代码的主要部分,# added
代表我为了尝试显示图表而添加的代码.查看值本身时,y
和 v
发生变化,x,z,u,w
保持 0.000
.当我运行程序时,轴刻度不断缩放,这意味着值发生了一些事情,但没有显示任何行.我究竟做错了什么?
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?
谢谢
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
推荐答案
诀窍是先累积要绘制的所有值,然后再调用一次 plot
.
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
要绘制的第三个参数'r-'
告诉 pylab
绘制一条红线,以连接 times
, yvals
.一次绘制点时,无法告诉 pylab
连接点,因为每个图仅包含一个点.为每个点调用 plot
也是非常低效的.
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.
这篇关于在python中绘制图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!