由于动态更新的性能问题,我需要在画布上直接绘制很多矩形作为非常低的级别,也就是说不使用matplotlib.patches,因为我们必须使用经典的GUI.
更准确地说,我想只绘制一个矩形,而不仅仅是所有的图形.
可能吗 ?
这是我使用Joe Kington给出的链接的测试代码.
#!/usr/bin/env python3
from random import randint, choice
import time
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.colors as colors
import matplotlib
back_color = "black"
colors = ['red', 'green', 'cyan', 'yellow']
width = 16
height = 16
ax = plt.subplot(111)
canvas = ax.figure.canvas
ax.set_xlim([0, width])
ax.set_ylim([0, height])
def update():
global ax, canvas, colors, width, height
x = randint(0, width - 1)
y = randint(0, height - 1)
rect = mpatches.Rectangle(
(x, y), 1, 1,
facecolor = choice(colors),
edgecolor = back_color
)
start = time.time()
ax.draw_artist(rect)
canvas.blit(ax.bbox)
print("draw >>>", time.time() - start)
timer = canvas.new_timer(interval = 1)
timer.add_callback(update)
timer.start()
plt.show()
在Mac O $下,我获得以下消息.
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/matplotlib/backend_bases.py", line 1203, in _on_timer
ret = func(*args, **kwargs)
File "/Users/xxx/test.py", line 86, in update
ax.draw_artist(rect)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/matplotlib/axes.py", line 2100, in draw_artist
a.draw(self._cachedRenderer)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/matplotlib/artist.py", line 56, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/matplotlib/patches.py", line 393, in draw
gc = renderer.new_gc()
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/matplotlib/backends/backend_macosx.py", line 97, in new_gc
self.gc.save()
RuntimeError: CGContextRef is NULL
对于Maverick用户
对于想要使用以下代码以及动画的Mac用户,我有一个好消息.我在没有任何软件的Mac上重新安装了Maverick OS,这称为干净安装,然后我安装了Anaconda和XQuark(see this).
要使动画有效,只需在任何其他matplotlib导入之前使用以下两行.
import matplotlib
matplotlib.use('TkAgg')
我认为这适用于Anaconda支持的任何Mac OS.只有Maverick才需要使用XQuark.