让我们今天做一个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里面的代码是判断这个小圆圈是否在这个指定的区域,如果是符合要求的区域,则按照指定的要求执行。