使用 matplotlib 绘制图形时出现间歇性错误 "RuntimeError: main thread is not in main loop"



我正在尝试使用我的python代码从不同的端点提取数据,并使用matplotlib提供相同的数据以绘制图形。 我在读取数据时没有任何问题,但是当我通过输入数据调用方法来绘制图形时,我看到由 matplot lib 引起的间歇性错误。以下是错误详细信息。

Traceback (most recent call last):
  File "C:Python35libsite-packagesslackbotdispatcher.py", line 55, in _dispatch_msg_handler
    func(Message(self._client, msg), *args)
  File "C:PycharmProjectsSlackBotsrcpluginsbot_response.py", line 248, in checkmarx
    draw_chart.riskscore_bar(top_riskscore, project_name, "output_files", "riskscore_bar.png")
  File "C:PycharmProjectsSlackBotsrcdrawchart.py", line 111, in riskscore_bar
    fig, ax = plt.subplots()
  File "C:Python35libsite-packagesmatplotlibpyplot.py", line 1202, in subplots
    fig = figure(**fig_kw)
  File "C:Python35libsite-packagesmatplotlibpyplot.py", line 535, in figure
    **kwargs)
  File "C:Python35libsite-packagesmatplotlibbackendsbackend_tkagg.py", line 81, in new_figure_manager
    return new_figure_manager_given_figure(num, figure)
  File "C:Python35libsite-packagesmatplotlibbackendsbackend_tkagg.py", line 98, in new_figure_manager_given_figure
    icon_img = Tk.PhotoImage(file=icon_fname)
  File "C:Python35libtkinter__init__.py", line 3403, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:Python35libtkinter__init__.py", line 3359, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
RuntimeError: main thread is not in main loop

尝试使用相同的错误消息查看堆栈溢出中的其他情况,但它没有帮助我解决这个问题。下面是我调用错误的代码片段。

def riskscore_bar(self, top_riskscore, project_id, output_folder, output_filename(:

logger.debug("Inside method plotgraph in drawchart.py.")
y_pos = np.arange(len(project_id))
width = .4
fig, ax = plt.subplots()
graph = ax.bar(y_pos+1, top_riskscore, width, color='#feb308')
ax.set_ylabel('Risk Score')
ax.set_title('Summary')
ax.set_xticks(y_pos + 1)
ax.set_xticklabels(project_id,fontsize=5, rotation=45 )
def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., 1.001*height,
                '%d' % int(height),
                ha='center', va='bottom')
autolabel(graph)
pylab.savefig(os.path.join(os.path.abspath(os.path.dirname(__file__)), '..', output_folder,output_filename))

错误似乎发生在"fig, ax = plt.subplots(("。 关于如何解决这个问题的任何想法?

可以通过在将matplotlib.pyplot导入PLT后立即在下面添加plt.switch_backend('agg'(来解决。如下图所示

import matplotlib.pyplot as plt    
plt.switch_backend('agg')

最新更新