如何从Django模板中的Matplotlib输出图形? [英] How to output a graph from Matplotlib in Django templates?

查看:1360
本文介绍了如何从Django模板中的Matplotlib输出图形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于此示例来自此处

  def simple(request):
import random

from matplotlib.backends.backend_agg import图CanCanvas $ C $ matplotlib.figure import图
从matplotlib.dates导入DateFormatter

fig =图()
ax = fig.add_subplot(111)
x = []
y = []
now = datetime.datetime.now()
delta = datetime.timedelta(days = 1)
for i in range(10):
x.append (现在)
now + = delta
y.append(random.randint(0,1000))
ax.plot_date(x,y,' - ')
ax.xaxis .set_major_formatter(DateFormatter('%Y-%m-%d'))
fig.autofmt_xdate()
canvas = FigureCanvas(fig)
response = django.http.HttpResponse(content_type = 'image / png')
canvas.print_png(响应)
返回响应

如何使用模板和变量来编写视图:
return render_to_response('template.html',{'graph':< ;由matplotlib生成的图形> }

解决方案

当我有类似的情况时,我使用了两个视图。一个使用matplotilb生成一个PNG,另一个使用django模板来创建一个呈现PNG(和其他一些数据)的HTML页面。发送到模板的参数只是PNG文件名。另一个视图然后附加到他适当的.png URL。



一个问题是如果要计算一些用于生成HTML和PNG的参数。我在文件名中编码了这样的信息。这是痛苦的,有点黑客,但如果所有的信息在文件名中保存,这对用户来说也是好的。


Given this example taken from here:

def simple(request):
    import random

    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    from matplotlib.dates import DateFormatter

    fig=Figure()
    ax=fig.add_subplot(111)
    x=[]
    y=[]
    now=datetime.datetime.now()
    delta=datetime.timedelta(days=1)
    for i in range(10):
        x.append(now)
        now+=delta
        y.append(random.randint(0, 1000))
    ax.plot_date(x, y, '-')
    ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
    fig.autofmt_xdate()
    canvas=FigureCanvas(fig)
    response=django.http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

How can I write the view in such a way that uses a template and variable like: return render_to_response ('template.html',{'graph': <graph generated by matplotlib> }

解决方案

When I had a similar situation, I used two views. One used matplotilb to generate a PNG, while the other used used django templates to create an HTML page that presented the PNG (and some other data). The param sent to the template was just the PNG filename. The other view is then attached to he appropriate .png URLs.

One problem is if you want to calculate some parameters which are used both for generating the HTML and PNG. I encoded such information in the filename. This is painful, and slightly hacky, but it's s also good for the user if all the info is in the filename when she saves it.

这篇关于如何从Django模板中的Matplotlib输出图形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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