通过 django 中的视图将 matplotlib 图形渲染到 html

Render matplotlib graph into html via views in django

我有一个 django 视图如下。我正在使用 matplotlib 生成条形图。

def myview(request, pk, sub):
    x=[1,2,3,4,5,6]
    y=[5,2,6,8,2,7]
    plot(x,y, linewidth=2)
    xlabel('x-axis')
    ylabel('yaxis')
    title('sample graph')
    grid(True)

    buffer = StringIO.StringIO()
    canvas = pylab.get_current_fig_manager().canvas
    canvas.draw()
    graphIMG = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb())
    graphIMG.save(buffer, "PNG")
    pylab.close()

    assgn = MyModel.objects.filter(data=pk, subject=sub)
    return render_to_response('mypage.html', {'assgn':assgn})

如何在 render_to_response 中传递条形图和查询?另外,我将如何在 html 中绘制此图?

您必须将绘图另存为图像文件并将 link 传递给此文件到您的模板。我不熟悉您使用的库,但我假设以下行会将图形保存到实际的 png 文件中:

graphIMG.save(buffer, "PNG")

保存到磁盘后,您应该有一个文件路径。确保 Django 可以访问此文件(即,将您的文件放在 settings.py 文件中 MEDIA_ROOT 指定的文件夹中)。

现在,将图表的路径传递给模板:

from django.shortcuts import render

def myview(request, pk, sub):
    ...
    imagepath = ...
    context = {'imagepath': imagepath}
    return render_to_response('mypage.html', context}

然后,在您的模板中:

<img src="{{ imagepath }}">

第一次尝试时您很可能不会得到它(即图像未显示)。要调试它,请打开您的网页并检查 link 到您的图像,复制 link 并将其粘贴到您的浏览器中,看看您是否可以访问它。如果没有,请检查您的 urls.py 并添加以下行,以便 Django 提供图像文件:

urlpatterns = patterns('',
    ...,

    url(r'^images/(.*)$', 'django.views.static.serve',
        {'document_root': settings.MEDIA_ROOT}), 
)

注意 r'^images/(.*)$' 部分,您的设置可能与我的不同。

这是文档:https://docs.djangoproject.com/en/1.4/howto/static-files/

该文档适用于 django 1.4(因此请单击您使用的版本),但它也适用于更高版本的 django。该文档还提供了此解决方案的 'shortcut' 版本。所以读它。

如文档中所述,此解决方案仅适用于开发。在生产中,您可能希望使用 apache 或 nginx 来提供静态内容。