python 如何在 Django 中使用 Matplotlib?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1874642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:15:25  来源:igfitidea点击:

How to use Matplotlib in Django?

pythondjangomatplotlib

提问by Hyman Ha

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 Matplotlibin Django? It looks like it remembers some drawings...

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

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

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

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).

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

回答by Cristian Ciupitu

You need to remove the numparameter from the figure constructorand closethe figure when you're done with it.

您需要num图形构造函数中删除参数并在完成后关闭图形。

import matplotlib.pyplot

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

By removing the numparameter, 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 clearmethod, i.e. f.clear().

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

回答by chenxuZhu

1.save picture which created by matplotlib
for example:plt.savefig('./app1/static/visualize.png') 2.use the picture in your html code for example:

1.保存由matplotlib创建的图片,
例如:plt.savefig('./app1/static/visualize.png') 2.在你的html代码中使用图片,例如:

about django how to use static variable(like picture and js file) you can refer to django document

关于django如何使用静态变量(如图片和js文件)可以参考django文档