今天我们做一个matplotLib的基础练习,就是让一个小球绕着figure界面绕圈圈。这个程序其实不需要动脑子,就是一些关于matplotLib的实际应用,并没有太多的技术含量,只需要稍微写点if语句就可以搞定的事情。
分析代码
一,先看代码(仅供学习)
from matplotlib import pylab
%pylab
%matplotlib notebook
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib.animation as animation
from matplotlib.patches import Circle, Rectangle
import matplotlib.lines as mlines
import matplotlib.image as mpimg
shapes=[]
fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(111)
circles={'a':{'x':0.1,'y':0.1,'r':0.01}}
def setup():
shapes.clear()
c=Circle((circles['a']['x'],circles['a']['y']), radius = circles['a']['r'], facecolor='black', edgecolor='none')
ax.add_patch(c)
shapes.append(c)
def update(frame_index):
if circles['a']['x']<0.9 and circles['a']['y']<0.11:
circles['a']['x']+=0.01
if circles['a']['x']>=0.9 and circles['a']['y']<0.9:
circles['a']['y']+=0.01
if circles['a']['y']>0.9 and circles['a']['x']>=0.1:
circles['a']['x']+=-0.01
if circles['a']['x']<=0.11 and circles['a']['y']<=0.92:
circles['a']['y']+=-0.01
shapes[0].set(center=(circles['a']['x'],circles['a']['y']))
return shapes
ani = animation.FuncAnimation(fig, update, interval=10, init_func=setup, frames=10000, blit=True)
plt.show()所以说这个代码不是特别特别长,我们一行一行的分析。
shapes=[]之前暂不用管他,可以直接复制,就是一段引入代码,没有什么实际的作用,只是引入这个包,一般的matplotLib代码前面写这一段问题不大。
shapes=[]的意思就是建立一个空列表,下面两行也没什么太大技术含量,就是建立一个6,6的画板,然后……就没有然后了。
然后下面那一段呢就是把circles的各个因素总结在一个字典里,待会引用就行了,setup里头的代码就是画一个圆,然后update里的代码就是判断这个小圆圈是不是在这个指定的区域里,如果是符合要求的区域,那就按指定要求去执行。
版权声明:本文为LOUIS_F_OWEN原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。