gpt4 book ai didi

python - 如何在 Django 网页中嵌入 matplotlib 图形?

转载 作者:太空狗 更新时间:2023-10-30 01:12:45 26 4
gpt4 key购买 nike

所以,请耐心等待,因为我对 Django、Python 和一般的 Web 开发还很陌生。我想要做的是显示我使用 matplotlib 制作的图表。我让它工作到主页自动重定向到图形的 png 的位置(基本上是浏览器中显示图形的选项卡)。但是,现在我想要的是看到带有简单嵌入图形的实际主页。换句话说,我想看到导航栏等,然后是网站正文中的图表。

到目前为止,我已经进行了搜索,并且对如何实现这一点有了一些想法。我在想的是有一个简单地返回图表的特殊 View 。然后,以某种方式从我将用于显示数据的模板中的 img src 标记访问此 png 图像。

图码:

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 %}

我现在得到的:

Current Page

最佳答案

我知道这个问题被标记为 matplotlib,但我需要做同样的事情并且我找到了 plotly更易于使用并且在视觉上也更吸引人。您可以简单地绘制一个图形,然后在 View 中获取图形的 html 代码:

# 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

在模板中做:

<div style="width:1000;height:100">
{{ graph_div|safe }}
</div>

关于python - 如何在 Django 网页中嵌入 matplotlib 图形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40534715/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com