Matplotlib使用blit切换艺术家

时间:2014-07-07 13:41:30

标签: python matplotlib

我希望根据按下的键有条件地向绘图场景显示/隐藏一些元素。我不希望因速度而重绘整个画布。因此我想使用blit技术。我试过了,但出于某种原因,我的背景没有恢复。 以下是我想要达到的一个简单示例:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.lines import Line2D
from matplotlib.patches import Rectangle
class LinePlot:
    def __init__(self):
        self.fig = plt.figure()
        'connect to all the events we need'
        self.cidpress = self.fig.canvas.mpl_connect(
                'key_press_event', self.on_keypress)
        self.line_drawn=False
        self.rectangle_drawn=False
    def plot(self):
        self.ax = self.fig.add_subplot(111)
        x=np.random.random(size=1000)
        y=np.random.random(size=1000)
        self.collection=self.ax.scatter(x,y,marker='+',color='red')
        plt.show()
        self.fig.canvas.draw()
    def on_keypress(self,event):
        if event.key=='r':
            if not self.line_drawn:
                self.line=Line2D([0,0.5],[0,1])
                self.ax.add_line(self.line)
                self.ax.draw_artist(self.line)
                self.fig.canvas.blit(self.ax.bbox)
                self.line_drawn=True
            else:
                self.line.set_animated(True)
                background=self.fig.canvas.copy_from_bbox(self.line.axes.bbox)
                self.line.set_animated(False)
                self.fig.canvas.restore_region(background)
                self.line_drawn=False                
                self.fig.canvas.blit(self.ax.bbox)
        if event.key=='b':
            if not self.rectangle_drawn:
                self.rect=Rectangle((0.1,0.2),0.2,0.3,facecolor='green')
                self.ax.add_patch(self.rect)
                self.ax.draw_artist(self.rect)
                self.fig.canvas.blit(self.ax.bbox)
                self.rectangle_drawn=True
            else:
                self.rect.set_animated(True)
                background=self.fig.canvas.copy_from_bbox(self.rect.axes.bbox)
                self.rect.set_animated(False)
                self.fig.canvas.restore_region(background)
                self.rectangle_drawn=False                
                self.fig.canvas.blit(self.ax.bbox)

p=LinePlot()
p.plot()

如果' r'按下键,该行应该出现/消失,如果' b'键被按下,矩形应该出现/消失。我做错了什么?

0 个答案:

没有答案