在Django中输出matplotlib生成的图片方法

yipeiwu_com6年前Python基础

下面的代码片段是直接在Django中输出matplotlib生成的图片,网上很多种方法都是先生成图片再调用,感觉不是那么直接。

环境:Python2.7,Django1.83

该文件为views.py文件,函数映射按实际设置。

from django.shortcuts import render
from django.http import HttpResponse

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

import random
import datetime

# Create your views here.
def gen_mat(request):
 fig=Figure(figsize=(6,6))
 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=FigureCanvasAgg(fig)
 response=HttpResponse(content_type='image/png')
 canvas.print_png(response)
 plt.close(fig)
 return response

以上这篇在Django中输出matplotlib生成的图片方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

基于wxPython的GUI实现输入对话框(2)

基于wxPython的GUI实现输入对话框(2)

接着上一篇基于wxPython的GUI输入对话框1,继续学习。 在程序输入中,有时会要求同时改变多个参数值,而且类型也不尽相同, 这时TextEntryDialog就显得不适用了.WxI...

python 定时器,轮询定时器的实例

python 定时器默认定时器只执行一次,第一个参数单位S,几秒后执行 import threading def fun_timer(): print('Hello Timer...

在python的类中动态添加属性与生成对象

本文将通过一下几个方面来一一进行解决       1、程序的主要功能       2...

Python 中开发pattern的string模板(template) 实例详解

定制pattern的string模板(template) 详解 string.Template的pattern是一个正则表达式, 可以通过覆盖pattern属性, 定义新的正则表达式....

Python对接六大主流数据库(只需三步)

Python对接六大主流数据库(只需三步)

作为近两年来最火的编程语言的python,受到广大程序员的追捧必然是有其原因的,如果要挑出几点来讲的话,第一条那就python语法简洁,易上手,第二条呢? 便是python有着极...