我如何(在 Python 中)使用 blitting 从绘图中删除 matplotlib 艺术家?

How can I (in Python) remove a matplotlib Artist from a plot by using blitting?

我可以使用 blitting 删除 matplotlib 艺术家,例如补丁吗?

    """Some background code:"""

    from matplotlib.figure import Figure
    from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas

    self.figure = Figure()
    self.axes = self.figure.add_subplot(111)
    self.canvas = FigureCanvas(self, -1, self.figure)

要使用 blit 向 matplotlib 图添加补丁,您可以执行以下操作:

    """square is some matplotlib patch"""

    self.axes.add_patch(square)
    self.axes.draw_artist(square)
    self.canvas.blit(self.axes.bbox)

这行得通。但是,我可以使用 blit 从情节中删除同一位艺术家吗? 我设法用 square.remove() 删除了它,我可以用 self.canvas.draw() 函数更新绘图。但是当然这很慢,我想改用 blitting.

    """square is some matplotlib patch"""

    square.remove()
    self.canvas.draw()

以下无效:

    square.remove()
    self.canvas.blit(self.axes.bbox)

删除块化对象的想法是再次块化同一区域,而不是事先绘制对象。您也可以删除它,这样如果 canvas 因任何其他原因重绘也不会被看到。

您忘记调用 restore_region 的问题的代码中似乎存在。有关 blitting 所需命令的完整集合,请参见例如

示例如下,如果单击鼠标左键则显示矩形,如果单击鼠标右键则删除矩形。

import matplotlib.pyplot as plt
import numpy as np

class Test:
    def __init__(self):
        self.fig, self.ax = plt.subplots()
        # Axis with large plot
        self.ax.imshow(np.random.random((5000,5000)))
        # Draw the canvas once
        self.fig.canvas.draw()
        # Store the background for later
        self.background = self.fig.canvas.copy_from_bbox(self.ax.bbox)
        # create square
        self.square = plt.Rectangle([2000,2000],900,900, zorder=3, color="crimson")
        # Create callback to mouse movement
        self.cid = self.fig.canvas.callbacks.connect('button_press_event', 
                                                     self.callback)
        plt.show()

    def callback(self, event):
        if event.inaxes == self.ax:
            if event.button == 1:
                # Update point's location            
                self.square.set_xy((event.xdata-450, event.ydata-450))
                # Restore the background
                self.fig.canvas.restore_region(self.background)
                # draw the square on the screen
                self.ax.add_patch(self.square)
                self.ax.draw_artist(self.square)
                # blit the axes
                self.fig.canvas.blit(self.ax.bbox)
            else:
                self.square.remove()
                self.fig.canvas.restore_region(self.background)
                self.fig.canvas.blit(self.ax.bbox)

tt = Test()