使用Func动画 Python
以下代码是从这里获取的,并根据我的需求进行了修改:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
import math
import linecache
fig = plt.figure()
ax = plt.axes(xlim=(0,600), ylim=(0,600))
line, = ax.plot([], [], lw=3, color='r')
mul=2*math.pi/3
samp_rate=10
print ax
def init():
line.set_data([], [])
return line,
def animate(i):
print i
global mul
global samp_rate
line1=linecache.getline("data.txt", i+1)
if i==0:
x = float(line1)*math.cos(0)
y = float(line1)*math.sin(0)
line.set_data(x, y)
return line,
else:
x=float(line1)*math.cos((i)*mul/samp_rate)
y=float(line1)*math.cos((i)*mul/samp_rate)
line.set_data(x, y)
return line,
anim = animation.FuncAnimation(fig, animate, init_func=init, interval=5, blit=True)
plt.show()
当我打印ax时,输出结果如下:
Axes(0.125,0.1;0.775x0.8)
我设置的值范围是从0到600,但限制却是0.775到0.8
?这是为什么呢?另外,我绘制的值是从100到400,而输出窗口是:
我哪里出错了呢?
编辑 1:
我稍微改了一下代码。现在我从一个列表中输入值,也就是说,我并没有打开文件来获取值,而是直接创建了一个包含这些值的列表。代码是:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
import math
import linecache
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0,600), ylim=(0,600))
line, = ax.plot([], [], lw=3, color='r')
mul=2*math.pi/3
samp_rate=10
print ax
def init():
line.set_data([], [])
return line,
def animate(i):
print i
global mul
global samp_rate
line1=linecache.getline("data.txt", i+1)
x=[some vlaues that I have to plot]
y=[some vlaues that I have to plot]
line.set_data(x, y)
i+=1
return line,
anim = animation.FuncAnimation(fig,animate,init_func=init,frames=200,interval=24,blit=True)
plt.show()
在这种情况下,输出结果如下:

而且当我进入animate函数时,打印i
的值时,输出结果是不断增加的。
我提供了大约2万的x值和同样数量的y值。正如你在截图中看到的,它并没有绘制出所有的点。我该如何绘制所有的点呢?
1 个回答
0
print(ax)
并不会给你 x 和 y 的范围,而是告诉你坐标轴在图中的位置。print
这个命令使用了 __str__
这个方法。在 IPython 中,你可以通过以下方式查看某个方法的文档:
In [16]: ax.__str__??
Source:
def __str__(self):
return "Axes(%g,%g;%gx%g)" % tuple(self._position.bounds)
你也可以通过以下方式获取坐标轴的位置:
In[4]:ax._position.bounds
Out[4]: (0.125, 0.099999999999999978, 0.77500000000000002, 0.80000000000000004)
如果你想获取坐标轴的 x 和 y 范围,可以使用:
In[2]: ax.get_ylim()
Out[2]: (0.0, 600.0)
In[3]: ax.get_xlim()
Out[3]: (0.0, 600.0)
我不太确定为什么线条没有显示出来,因为我看不到 data.txt 的内容。我建议你检查一下 line1
是否是你预期的那样。