我在圆内绘制网格,当我选择任何网格时,我将在矩形上添加一个矩形对象。但是,当网格数很大(超过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()