1

我可以使用 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)
4

1 回答 1

3

删除 blitted 对象的想法是再次 blit 相同的区域,而不是事先绘制对象。您也可以删除它,这样如果由于任何其他原因重新绘制画布,它也不会被看到。

似乎在您忘记调用问题的代码中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()
于 2018-03-12T14:36:29.110 回答