当blit = True时,matplotlib动画保留旧补丁

时间:2016-11-11 13:44:04

标签: python animation matplotlib

我想在matplotlib中设置一个随机矩形的动画。我发现当我设置blit = True时,动画总是保持第一个矩形的计算。如果我设置blit = False,动画将继续更新矩形,旧矩形消失。如果我想设置blit = True,如何删除旧矩形?

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
import random

class box_sim_env(object):
    def __init__(self):
        self.env_fig = plt.figure()
        self.ax = self.env_fig.add_subplot(111, aspect='equal')

        self.box_pose = np.array([0.48, 0.5, 0])
        self.create_box(self.box_pose)
        self.ax.add_patch(self.box_patch)

    def update_box(self, pose):
        self.box_verts = self.get_rect_verts(np.array([pose[0], pose[1]]), 0.6, 0.3,
                                               angle=pose[2])
        self.box_patch.set_xy(self.box_verts)

    def create_box(self, pose):

        self.box_verts = self.get_rect_verts(np.array([pose[0], pose[1]]), 0.6, 0.3,
                                               angle=pose[2])   
        self.box_patch = plt.Polygon(self.box_verts, facecolor='cyan', edgecolor='blue')

    def get_rect_verts(self, center, length, width, angle):
        rotation_mtx = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
        half_length = length / 2.0
        half_width = width / 2.0
        verts = np.array([[-half_length, half_width],
                          [half_length, half_width],
                          [half_length, -half_width],
                          [-half_length, -half_width]])
        verts_rot = np.dot(rotation_mtx, verts.T)
        verts_trans = verts_rot.T + center.reshape((1,2))
        return verts_trans.reshape((4,2))      

    def animate(self, i):
        pose = np.zeros(3)
        pose[0] = random.uniform(-3,3)
        pose[1] = random.uniform(-3,3)
        pose[2] = random.uniform(-np.pi, np.pi)
        self.update_box(pose)
        return [self.box_patch,]

    def plt_show(self):
        self.anim = animation.FuncAnimation(self.env_fig, self.animate,
                                       init_func=None,
                                       frames=1000,
                                       interval=1,
                                       # repeat= False,
                                       blit=True)

        plt.xlim([-4,4])
        plt.ylim([-4,4])
        plt.show()

if __name__ == '__main__':
    print '============'
    box_sim = box_sim_env()
    box_sim.plt_show()

0 个答案:

没有答案