【问题标题】:Matplotlib hangs in DjangoMatplotlib 在 Django 中挂起
【发布时间】:2015-04-14 09:53:53
【问题描述】:

我正在尝试绘制一些由 Matplotlib 生成的图表,但我发现虽然它第一次正常工作,但如果我刷新我的页面,Matplotlib 将在其内部工作(Tkinter.py ) 创建图窗 (plt.figure) 时。我已经设法通过以下小示例缩小了问题范围..

模板(只需要这一行)

<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})

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

【问题讨论】:

    标签: python django matplotlib tkinter


    【解决方案1】:

    问题原来是使用错误后端的问题...问题已通过 jenshnielsen's suggestion 解决,以在导入 pyplot 之前更改正在使用的后端

    import matplotlib
    matplotlib.use('agg')
    

    Jens,如果你读到这篇文章,请发表你自己的答案,我很乐意删除这个!

    【讨论】:

      猜你喜欢
      • 2013-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-04
      • 1970-01-01
      • 2015-12-02
      • 1970-01-01
      相关资源
      最近更新 更多