如何在Django网页中嵌入matplotlib图? [英] How to embed matplotlib graph in Django webpage?
问题描述
因此,请耐心等待,因为我是Django,Python和网络开发的新手。我要做的是显示我使用matplotlib制作的图形。我让它工作到主页自动重定向到图形的png的位置(基本上是浏览器中显示图形的选项卡)。但是,现在我要查看的是简单嵌入图形的实际主页。换句话说,我想查看导航栏等,然后再查看网站正文中的图形。
So, bear with me as I'm VERY new to Django, Python, and web-development in general. What I want to do is display a graph that I've made using matplotlib. I had it working to where the home page automatically redirects to the png of the graph (basically a tab in the browser with the graph displayed). However, now what I want is to see the actual homepage with the graph simply embedded. In other words, I want to see the navigation bar, etc. and then the graph in the body of the site.
到目前为止,我已经进行了搜索,并且对如何实现此目标有所了解。我在想一种特殊的视图,它只返回图形。然后,以某种方式从模板中的img src标记访问此png图像,该图像将用于显示数据。
So far, I've searched and I sort of have an idea of how to accomplish this. What I'm thinking is having a special view that simply returns the graph. Then, somehow accessing this png image from an img src tag in my template that I will use to display my data.
图形代码:
from django.shortcuts import render
import urllib
import json
from django.http import HttpResponse
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import datetime as dt
import pdb
def index(request):
stock_price_url = 'https://www.quandl.com/api/v3/datatables/WIKI/PRICES.json?ticker=GOOGL&date.gte=20151101&qopts.columns=date,close&api_key=KEY'
date = []
price = []
#pdb.set_trace()
source_code = urllib.request.urlopen(stock_price_url).read().decode()
json_root = json.loads(source_code)
json_datatable = json_root["datatable"]
json_data = json_datatable["data"]
for day in json_data:
date.append(dt.datetime.strptime(day[0], '%Y-%m-%d'))
price.append(day[1])
fig=Figure()
ax = fig.add_subplot(1,1,1)
ax.plot(date, price, '-')
ax.set_xlabel('Date')
ax.set_ylabel('Price')
ax.set_title("Google Stock")
canvas = FigureCanvas(fig)
response = HttpResponse(content_type='image/png')
#canvas.print_png(response)
return response
模板代码:
{% extends "home/header.html" %}
{% block content %}
<p>Search a stock to begin!</p>
<img src="home/graph.py" />
{% endblock %}
我现在得到的是:
推荐答案
我知道这个问题被标记为matplotlib,但是我需要做同样的事情,并且发现 plotly 以便更易于使用和吸引人。您可以简单地绘制图形,然后在视图中获取图形的html代码,如下所示:
I know this question is tagged as matplotlib, but I needed to do the same thing and I have found plotly to be easier to use and appealing as well. You can simply plot a graph and then in the view get the html code of the graph as :
# fig is plotly figure object and graph_div the html code for displaying the graph
graph_div = plotly.offline.plot(fig, auto_open = False, output_type="div")
# pass the div to the template
在模板中执行以下操作:
In the template do:
<div style="width:1000;height:100">
{{ graph_div|safe }}
</div>
这篇关于如何在Django网页中嵌入matplotlib图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!