如何在Django中使用Matplotlib? [英] How to use Matplotlib in Django?

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

问题描述

从互联网的一些例子,我做了下面的测试代码。有用!



...但是,如果我重新加载页面,饼图将使用相同的图像绘制自己。每次重新加载页面时,某些部分会变暗。当我重新启动开发服务器,它被重置。 Django中的 Matplotlib 如何正确绘制?看起来它记得一些图纸...



源views.py(让urls.py链接到它):



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $


$ b def test_matplotlib(request) b $ bf = figure(1,figsize =(6,6))
ax = axes([0.1,0.1,0.8,0.8])
labels ='Frogs','Hogs','Dogs ','Logs'
fracs = [15,30,45,10]
explode =(0,0.05,0,0)
pie(fracs,explode = explode,labels = labels ,autopct ='%1.1f %%',shadow = True)
title('Raining Hogs and Dogs',bbox = {'facecolor':'0.8','pad':5})

canvas = FigureCanvasAgg(f)
response = HttpResponse(content_type ='image / png')
canvas.print_png(响应)
返回响应

我正在使用Django 1.0.1和Python 2.6.2(Linux)。

解决方案

你需要删除 num 参数从图构造函数关闭,当你

  import matplotlib.pyplot 

def test_matplotlib(request):
f = figure(figsize =(6,6))
....
matplotlib.pyplot.close(f)

通过删除 num 参数,您将避免同时使用相同的数字。如果2个浏览器同时请求图像,则可能会发生这种情况。如果这不是问题,另一个可能的解决方案是使用清除方法,即 f.clear()


From some examples from the Internet I made the test code below. It works!

... BUT if I reload the page, the pie will draw itself with the same image. Some parts get darker every time I reload the page. When I restart the the development server, it is reset. How do I draw properly with Matplotlib in Django? It looks like it remembers some drawings...

Source views.py (let urls.py link to it):

from pylab import figure, axes, pie, title
from matplotlib.backends.backend_agg import FigureCanvasAgg

def test_matplotlib(request):
    f = figure(1, figsize=(6,6))
    ax = axes([0.1, 0.1, 0.8, 0.8])
    labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
    fracs = [15,30,45, 10]
    explode=(0, 0.05, 0, 0)
    pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
    title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})

    canvas = FigureCanvasAgg(f)    
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

I am using Django 1.0.1 and Python 2.6.2 (Linux).

解决方案

You need to remove the num parameter from the figure constructor and close the figure when you're done with it.

import matplotlib.pyplot

def test_matplotlib(request):
    f = figure(figsize=(6,6))
    ....
    matplotlib.pyplot.close(f)

By removing the num parameter, you'll avoid using the same figure at the same time. This could happen if 2 browsers request the image at the same time. If this is not an issue, another possible solution is to use the clear method, i.e. f.clear().

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

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