Matplotlib挂在Django中 [英] Matplotlib hangs in Django

查看:50
本文介绍了Matplotlib挂在Django中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试绘制由Matplotlib生成的一些图表,但我发现虽然第一次正常运行,但如果刷新页面,则Matplotlib只会挂在 _tkinter.create 的深处创建图形( plt.figure )时,其内部工作原理(Tkinter.py).我通过下面的小示例设法缩小了问题的范围.

I'm trying to draw some charts generated by Matplotlib but I am finding that whilst it works correctly the first time, if I refresh my page, Matplotlib will just hang on _tkinter.create deep within its inner workings (Tkinter.py) when creating the figure (plt.figure). I've managed to narrow down the issue with the following small example..

模板(仅需要这一行)

<img src="data:image/png;base64,{{ graph }}"/>

图表创建

class PolarChart(object):    
    @staticmethod
    def example_chart():
        from math import pi, radians
        import cStringIO
        import base64  
        import numpy as np
        import matplotlib.pyplot as plt

        fig = plt.figure()    
        axis = fig.gca(polar=True)

        n = 20
        theta = np.linspace(0.0, 2 * pi, n, endpoint=False)
        radii = 10 * np.random.rand(n)

        axis.plot(theta, radii, marker='.', alpha=0.5, linewidth=1)

        jpg_image_buffer = cStringIO.StringIO()
        fig.savefig(jpg_image_buffer)

        plt.close(fig)
        base_array = base64.b64encode(jpg_image_buffer.getvalue())
        jpg_image_buffer.close()

        return base_array

查看

graph = PolarChart.example_chart()

return render(request, "test.html", {'graph': graph})

建议使用 fig.clear()进行其他stackoverflow问题,但这也会导致页面无法呈现(相同的悬挂效果)

Other stackoverflow questions have suggested using fig.clear() but this also results in the page not rendering (the same hanging effect)

推荐答案

事实证明该问题与使用错误的后端有关...通过

The issue turned out to be an issue with using the wrong backend... The issue was resolved with jenshnielsen's suggestion to change the backend that is being used before importing pyplot

import matplotlib
matplotlib.use('agg')

Jens,如果您阅读此内容,请发表您自己的答案,我会很乐意删除此答案!

这篇关于Matplotlib挂在Django中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆