【问题标题】:Matplotlib draw_artist(axis.patch) fails on MacOSX backendMatplotlib draw_artist(axis.patch) 在 MacOSX 后端失败
【发布时间】:2016-08-10 20:45:07
【问题描述】:

我正在关注Speeding up Matplotlib -- Bastibe,通过仅更新图中已更改的内容来测试制作动画。我正在使用 MacPorts 安装的 Mac OS X 10.11.4、Python 3.4。代码如下:

'''Import modules'''
import matplotlib.pyplot as plt
import numpy as np
import time

'''Initialize figure and axis, perform first draw on canvas'''
fig, ax = plt.subplots()
line, = ax.plot(np.random.randn(100))
plt.show(block=False)
fig.canvas.draw()

'''Count how many plots made within 1 second'''
tstart = time.time()
num_plots = 0
while time.time()-tstart < 1:            # within 1 second
    line.set_ydata(np.random.randn(100)) # update line
    ax.draw_artist(ax.patch)             # draw background
    ax.draw_artist(line)                 # draw line
    fig.canvas.update()                  # update canvas
    fig.canvas.flush_events()
    num_plots += 1                       # count++
print(num_plots)

此代码在带有 Python 3.4 + Qt5Agg 后端的 Ubuntu 14.04 上运行良好。但在 Mac 上,它会报告

Traceback (most recent call last):
  File "./test.py", line 19, in <module>
    ax.draw_artist(ax.patch)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/matplotlib/axes/_base.py", line 2340, in draw_artist
    a.draw(self._cachedRenderer)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/matplotlib/artist.py", line 61, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/matplotlib/patches.py", line 486, in draw
    gc = renderer.new_gc()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/matplotlib/backends/backend_macosx.py", line 99, in new_gc
    self.gc.save()
RuntimeError: CGContextRef is NULL

欢迎提出任何建议!

【问题讨论】:

    标签: macos python-3.x matplotlib runtime-error


    【解决方案1】:

    您需要使用不同的后端。 将这些行添加到脚本的开头:

    import matplotlib
    
    matplotlib.use('Qt4Agg')
    

    这给了我 283 个图,而 fig.canvas.draw() 只给了 26 个图。

    【讨论】:

    • 好建议迈克。内核必须重新启动,否则 matplotlib 会抱怨 matplotlib.use('Qt4Agg') 无效,因为已经选择了后端。您还需要关闭绘图 plt.close() 否则它会挂在那里。
    • 谢谢你。事实上,我知道 Qt 后端可以工作,但我仍然想知道原始 MacOSX 后端有什么问题。或者我应该问一下使用 Qt 后端而不是原来的后端是否有一些优势?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    • 2014-02-20
    • 1970-01-01
    相关资源
    最近更新 更多