首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >高效Matplotlib重绘

高效Matplotlib重绘
EN

Stack Overflow用户
提问于 2015-03-26 11:18:02
回答 1查看 14.4K关注 0票数 18

我使用Matplotlib允许用户使用mouseclicks选择有趣的数据点,使用与this answer.非常类似的方法

有效地,散点图显示在热图图像和鼠标点击可以添加或删除散点点。

我的数据是使用pcolormesh()在后台绘制的,所以当我使用axis.figure.canvas.draw()更新画布时,散射点和背景热图都会被重新绘制。考虑到热图的大小,这对于可用的接口来说太慢了。

是否有一种有选择地重新绘制散点图而不重新绘制背景的方法?

示例代码:

代码语言:javascript
运行
复制
points = []  # Holds a list of (x,y) scatter points 

def onclick(event):
    # Click event handler to add points
    points.append( (event.x, event.y) )
    ax.figure.canvas.draw()

fig = plt.figure()
ax = plt.figure()
# Plot the background
ax.pcolormesh(heatmap_data)

# Add the listener to handle clicks
cid = fig.canvas.mpl_connect("button_press_event", onclick)
plt.show()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-26 16:50:07

好的!你想要的是闪电战。如果您没有编写gui,您可以使用matplotlib.animation简化其中的一些操作,但是如果您想让事情具有交互性,则需要直接处理它。

在matplotlib术语中,您需要fig.canvas.copy_from_bbox的组合,然后交替调用fig.canvas.restore_region(background)ax.draw_artist(what_you_want_to_draw)fig.canvas.blit

代码语言:javascript
运行
复制
background = fig.canvas.copy_from_bbox(ax.bbox)

for x, y in user_interactions:
    fig.canvas.restore_region(background)
    points.append([x, y])
    scatter.set_offsets(points)
    ax.draw_artist(scatter)
    fig.canvas.blit(ax.bbox)

简单的切分示例:添加点

在您的情况下,如果您只是添加点,您实际上可以跳过保存和恢复背景。但是,如果你走这条路,你最终会对情节做一些微妙的改变,因为反别名的点会被反复地重新画在另一个上面。

无论如何,这里是你想要的东西类型的最简单的例子。这只涉及添加点,并跳过前面提到的保存和恢复背景:

代码语言:javascript
运行
复制
import matplotlib.pyplot as plt
import numpy as np

def main():
    fig, ax = plt.subplots()
    ax.pcolormesh(np.random.random((100, 100)), cmap='gray')

    ClickToDrawPoints(ax).show()

class ClickToDrawPoints(object):
    def __init__(self, ax):
        self.ax = ax
        self.fig = ax.figure
        self.xy = []
        self.points = ax.scatter([], [], s=200, color='red', picker=20)
        self.fig.canvas.mpl_connect('button_press_event', self.on_click)

    def on_click(self, event):
        if event.inaxes is None:
            return
        self.xy.append([event.xdata, event.ydata])
        self.points.set_offsets(self.xy)
        self.ax.draw_artist(self.points)
        self.fig.canvas.blit(self.ax.bbox)

    def show(self):
        plt.show()

main()

有时简单太简单了

然而,假设我们想要使右键删除一个点。

在这种情况下,我们需要能够恢复背景而不重新绘制它。

好的,一切都很好。我们将使用类似于我在答案顶部提到的伪代码片段。

然而,有一个警告:如果数字被调整大小,我们需要更新背景。同样,如果轴是交互缩放/平移,我们需要更新背景。基本上,你需要更新的背景,随时绘制的情节。

很快你就需要变得相当复杂。

更复杂:添加/拖动/删除点

这是一个一般的“脚手架”的例子,你最终会把它放在适当的位置。

这有点低效,因为情节被绘制了两次。(例如,摇水会很慢)。这是可能的,但我将把这些例子留到下一次。

这实现了添加点、拖动点和删除点。若要在交互式缩放/平移后添加/拖动一个点,请单击工具栏上的缩放/pan工具再次禁用它们。

这是一个相当复杂的例子,但希望它能给出一种框架类型的感觉,这种框架通常用于交互式绘制/拖动/编辑/删除matplotlib艺术家,而不需要重新绘制整个情节。

代码语言:javascript
运行
复制
import numpy as np
import matplotlib.pyplot as plt

class DrawDragPoints(object):
    """
    Demonstrates a basic example of the "scaffolding" you need to efficiently
    blit drawable/draggable/deleteable artists on top of a background.
    """
    def __init__(self):
        self.fig, self.ax = self.setup_axes()
        self.xy = []
        self.tolerance = 10
        self._num_clicks = 0

        # The artist we'll be modifying...
        self.points = self.ax.scatter([], [], s=200, color='red',
                                      picker=self.tolerance, animated=True)

        connect = self.fig.canvas.mpl_connect
        connect('button_press_event', self.on_click)
        self.draw_cid = connect('draw_event', self.grab_background)

    def setup_axes(self):
        """Setup the figure/axes and plot any background artists."""
        fig, ax = plt.subplots()

        # imshow would be _much_ faster in this case, but let's deliberately
        # use something slow...
        ax.pcolormesh(np.random.random((1000, 1000)), cmap='gray')

        ax.set_title('Left click to add/drag a point\nRight-click to delete')
        return fig, ax

    def on_click(self, event):
        """Decide whether to add, delete, or drag a point."""
        # If we're using a tool on the toolbar, don't add/draw a point...
        if self.fig.canvas.toolbar._active is not None:
            return

        contains, info = self.points.contains(event)
        if contains:
            i = info['ind'][0]
            if event.button == 1:
                self.start_drag(i)
            elif event.button == 3:
                self.delete_point(i)
        else:
            self.add_point(event)

    def update(self):
        """Update the artist for any changes to self.xy."""
        self.points.set_offsets(self.xy)
        self.blit()

    def add_point(self, event):
        self.xy.append([event.xdata, event.ydata])
        self.update()

    def delete_point(self, i):
        self.xy.pop(i)
        self.update()

    def start_drag(self, i):
        """Bind mouse motion to updating a particular point."""
        self.drag_i = i
        connect = self.fig.canvas.mpl_connect
        cid1 = connect('motion_notify_event', self.drag_update)
        cid2 = connect('button_release_event', self.end_drag)
        self.drag_cids = [cid1, cid2]

    def drag_update(self, event):
        """Update a point that's being moved interactively."""
        self.xy[self.drag_i] = [event.xdata, event.ydata]
        self.update()

    def end_drag(self, event):
        """End the binding of mouse motion to a particular point."""
        for cid in self.drag_cids:
            self.fig.canvas.mpl_disconnect(cid)

    def safe_draw(self):
        """Temporarily disconnect the draw_event callback to avoid recursion"""
        canvas = self.fig.canvas
        canvas.mpl_disconnect(self.draw_cid)
        canvas.draw()
        self.draw_cid = canvas.mpl_connect('draw_event', self.grab_background)

    def grab_background(self, event=None):
        """
        When the figure is resized, hide the points, draw everything,
        and update the background.
        """
        self.points.set_visible(False)
        self.safe_draw()

        # With most backends (e.g. TkAgg), we could grab (and refresh, in
        # self.blit) self.ax.bbox instead of self.fig.bbox, but Qt4Agg, and
        # some others, requires us to update the _full_ canvas, instead.
        self.background = self.fig.canvas.copy_from_bbox(self.fig.bbox)

        self.points.set_visible(True)
        self.blit()

    def blit(self):
        """
        Efficiently update the figure, without needing to redraw the
        "background" artists.
        """
        self.fig.canvas.restore_region(self.background)
        self.ax.draw_artist(self.points)
        self.fig.canvas.blit(self.fig.bbox)

    def show(self):
        plt.show()

DrawDragPoints().show()
票数 29
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29277080

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档