Fast update of single points in a plot

前端 未结 1 2048

I have a matplotlib figure in which I have several plots. One has an image with a large number of points in it. The second has an axis in which I want to update a point loc

相关标签:
1条回答
  • 2021-01-07 14:11

    You are essentially ignoring most of what is needed for blitting. See e.g.

    • why is plotting with Matplotlib so slow?
    • Fast Live Plotting in Matplotlib / PyPlot

    As usual you need to

    • Draw the canvas, fig.canvas.draw()
    • Store the background for later, fig.canvas.copy_from_bbox()
    • Update the point, point.set_data
    • Restore the background, fig.canvas.restore_region
    • draw the point, ax.draw_artist
    • blit the axes, fig.canvas.blit

    Hence

    import matplotlib.pyplot as plt
    import numpy as np
    
    class Test:
        def __init__(self):
            self.fig = plt.figure(1)
            # Axis with large plot
            self.ax_large = plt.subplot(121)
            self.ax_large.imshow(np.random.random((5000,5000)))
            # Follow the point
            self.ax = plt.subplot(122)
            self.ax.grid(True)
    
            # set some limits to the axes
            self.ax.set_xlim(-5,5)
            self.ax.set_ylim(-5,5)
            # Draw the canvas once
            self.fig.canvas.draw()
            # Store the background for later
            self.background = self.fig.canvas.copy_from_bbox(self.ax.bbox)
            # Now create some point
            self.point, = self.ax.plot(0,0, 'go')
            # Create callback to mouse movement
            self.cid = self.fig.canvas.callbacks.connect('motion_notify_event', 
                                                         self.callback)
            plt.show()
    
        def callback(self, event):
            if event.inaxes == self.ax:
                # Update point's location            
                self.point.set_data(event.xdata, event.ydata)
                # Restore the background
                self.fig.canvas.restore_region(self.background)
                # draw the point on the screen
                self.ax.draw_artist(self.point)
                # blit the axes
                self.fig.canvas.blit(self.ax.bbox)
    
    
    tt = Test()
    
    0 讨论(0)
提交回复
热议问题