python-3.x - 如何在不重绘图形的情况下更新绘图
问题描述
我在一个圆圈内绘制网格,当我选择任何网格时,我会在圆圈中添加一个矩形对象。但是当网格数量很大(超过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()
解决方案
推荐阅读
- java - 无法检查数组中的所有元素
- javascript - select2 .select2('data', {id: '', text: ''}) 不起作用
- c++ - hackerrank Ramanujan 的 Prime Substrings 1 问题
- java - java fx - 不同的行为取决于上下文
- swift - 在 SFSpeechRecognizer 中使用 AudioToolbox 而不是 AVFoundation
- javascript - 加载本地 Json 文件并使用 Javascript 将其存储在变量中
- flutter - 水平模式下的 Flutter ButtonBar 似乎不尊重 MainAxisSize
- api - Google Geocoding API - 根据邮政编码返回任何有效地址
- python - 使用 Keras 序列生成器和 fit_generator 时的层尺寸问题
- c# - 在 MDI 父窗体的面板中打开 Windows 子窗体