首页 > 解决方案 > 如何在不重绘图形的情况下更新绘图

问题描述

我在一个圆圈内绘制网格,当我选择任何网格时,我会在圆圈中添加一个矩形对象。但是当网格数量很大(超过40000)并且添加了很多矩形时,绘图时间会很长。

我认为这是因为每次添加矩形时,我都会重绘图形。所以我认为如果我可以更新图形而不重绘它,它会快得多。但是,不幸的是,我在 matplotlib 中找不到任何 api。有没有人有任何想法来解决这个问题?谢谢 !

这是我的代码的一部分:

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np

def onclick(event):
    """add Rectangle when click any gird on circle"""
    try:
        rect = patches.Rectangle((int(event.mouseevent.xdata), int(event.mouseevent.ydata)), 1, 1, facecolor=(.7, .9, .9, .9), edgecolor=(.2, .1, .1,.5))
        ax.add_patch(rect)
        rect.set_clip_path(circ)
        # redraw can update the figure, but it would take long time
        fig.canvas.draw()
    except Exception as e:
        print(e.args)


r = 50  # radius
fig = plt.figure()
ax = plt.gca()
plt.grid(True)

circ = patches.Circle((0, 0), radius=r,
                      facecolor=(.5, .5, .5), edgecolor='black', picker=5)
ax.add_patch(circ)

# Fill half of circle with rectagles
for x in range(int(-r/2), int(r/2)):
    for y in range(int(-r/2), int(r/2)):
        if x + y < r * r:
            rect = patches.Rectangle((x, y), 1, 1, facecolor=(.7, .5, .5, .5), edgecolor=(.2, .1, .1, .5))
            ax.add_patch(rect)
            rect.set_clip_path(circ)

fig.canvas.mpl_connect('pick_event', onclick)

# Diable any ticks and labels
plt.tick_params(
    axis='both',
    left='off',
    bottom='off',
    labelleft='off',
    labelbottom='off'
)
plt.xlim([-r-1, r+1])
plt.ylim([-r-1, r+1])
plt.xticks(np.arange(-r-1, r+1))
plt.yticks(np.arange(-r-1, r+1))
plt.setp(ax.xaxis.get_gridlines(), clip_path=circ)
plt.setp(ax.yaxis.get_gridlines(), clip_path=circ)

plt.axes().set_aspect('equal')
plt.show()

标签: python-3.xmatplotlib

解决方案


推荐阅读