【问题标题】:Python - How to output matplotlib plots as images to the browser in DjangoPython - 如何在 Django 中将 matplotlib 图作为图像输出到浏览器
【发布时间】:2017-03-24 18:16:58
【问题描述】:

我正在使用 Python-Pandas、Numpy 来实现一些财务指标和策略。我还在 Python 中使用 Matlab 库来绘制我的数据。

另一方面,我将 Django 用于我的项目的 Web 端部分。

我想要做的是使用 Django 将我的 matlab 图作为图像输出到浏览器。

感谢任何建议。 非常感谢!

【问题讨论】:

标签: python django matplotlib plot


【解决方案1】:

这似乎是一个老问题,并且有一段时间没有活动,但我最近遇到了类似的问题。我能够解决它,所以我想我可以分享我的解决方案。就这样吧。 在您的 html 模板中,您应该有一个按钮来触发 ajax 请求。例如:

***index.html***

<a href="#" id="plot">Plot</a>

<div id="imagediv"></div>

$('#plot').click(function(){
$.ajax({
        "type"     : "GET",
        "url"      : "/Plot/",
        "data"     : "str",
        "cache"    : false,
        "success"  : function(data) {
            $('#imagediv').html(data);
        }
});

});

你的views.py(或者一个单独的文件,例如:utils.py)应该有一个绘制图表的函数。

***utils.py***

@login_required()
def MatPlot(request):
    # Example plot
    N = 50
    x = np.random.rand(N)
    y = np.random.rand(N)
    colors = np.random.rand(N)
    area = np.pi * (15 * np.random.rand(N)) ** 2
    plt.scatter(x, y, s=area, c=colors, alpha=0.5)
    # The trick is here.
    f = io.BytesIO()
    plt.savefig(f, format="png", facecolor=(0.95, 0.95, 0.95))
    encoded_img = base64.b64encode(f.getvalue()).decode('utf-8').replace('\n', '')
    f.close()
    # And here with the JsonResponse you catch in the ajax function in your html triggered by the click of a button
return JsonResponse('<img src="data:image/png;base64,%s" />' % encoded_img, safe=False)

当然你需要用一个url来连接这个函数,所以:

***urls.py***
url(r'^plot/$', Matplot, name='matplot')

【讨论】:

  • 这对我来说效果很好!我只是有一个问题要问你。使用 Base64 编码是否会给客户端和/或服务器带来更大的压力?
猜你喜欢
  • 2011-07-25
  • 2014-11-24
  • 2012-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-22
相关资源
最近更新 更多