在Django主页中添加动态生成的matplotlib图片 [英] Add a dynamically generated matplotlib picture in Django home

查看:69
本文介绍了在Django主页中添加动态生成的matplotlib图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在家里添加动态生成的图片.我不想保存该图,而是在一些文本之后直接在我的主页中显示它.我的 views.py 如下:

I would like to add a dynamically generated picture in my home. I do not want to save the figure, but just show it directly in my home page, after some text. My views.py looks like:

from django.shortcuts import render
def index(request):
    import random
    import datetime
    import django
    import pylab 
    import PIL, PIL.Image
    import io

    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)
    graphic1  =django.http.HttpResponse(content_type='image/png')
    canvas.print_png(graphic1)
    return render(request, 'personal/home.html',{'graphic':graphic1}) 

功能 index 已包含在 urls.py 中.没问题.我的 home.html 看起来像

Function index is already included in the urls.py. No problem there. My home.html looks like

{% extends "personal/header.html" %}
{% block content %}
<p> Welcome to my website!</p>
{% include "personal/includes/htmlpic.html" %}
{% endblock %}  

我的 htmlpic.html 是:

{% block graphic  %}
<div id="content">
    <img src= "data:image/png;base64,{{graphic|safe}}" >
</div>
{% endblock %}

错误:未显示该图.像这样的断开链接:

The error: the figure does not show up. It is a broken link like this:

<img src="data:image/png;base64,&lt;HttpResponse status_code=200, " image png">

它清楚地复制了状态而不是二进制图像(并添加了额外的引号).你能告诉我我在做什么错吗?还是提出类似的问答?

It clearly copies the status instead of the image in binary (and adds an extra quote). Can you tell me what I am doing wrong here? Or suggest a SO similar Q&A?

PS.我是Django的新手,请大方.

PS. I'm a newbie in Django, please be generous.

推荐答案

以我的经验,在这种情况下,实际上并不需要它们.只需创建一个单独的视图即可返回图像.为了简单起见,我在这里使用 gnuplot .该命令仅将正弦函数的png图像打印到标准输出.(此处是一些有关从matplotlib画布.)在 views.py 中:

In this case, there is no real need for them anyway. Just create a separate view that returns the image. I am using gnuplot here for simplicity. The command just prints a png image of a sine function to the stdout. (Here are some instructions on getting the image data from a matplotlib canvas.) In views.py:

def my_plot(request):
    import subprocess
    plot = subprocess.check_output(['gnuplot', '-e', 'set terminal pngcairo; plot sin(x)'])
    response = HttpResponse(plot, content_type="image/png")
    return response

假设您将此视图映射到网址 plot ,因此编写 urls.py 如下所示:

Say you map this view to url plot, therefore writing the urls.py as in here:

urlpatterns = patterns(
    '',

    url(r'^$', views.index, name='home'),

    url(r'^plot$', views.my_plot, name='plot')
)

然后,您可以简单地使用生成图像的视图作为图像源.在 htmlpic.html 中:

Then you can simply use the view that generates the image as the source of your image. In htmlpic.html:

<img src="plot"></img>

对我来说,这是一个更加清晰的关注点分离.一个视图渲染您的模板,另一个视图渲染图像.如果您希望将此图像嵌入到程序中的其他位置,则可以通过这种方式不必重复自己的操作.

To me this is a much clearer separation of concerns. One view renders your template, the other renders the image. If you wish to embed this image somewhere else in your program, this way allows you to do so without repeating yourself.

这篇关于在Django主页中添加动态生成的matplotlib图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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