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

标签 python django matplotlib graph

所以,请耐心等待,因为我对 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/

相关文章:

python multiprocessing starmap vs apply_async,哪个更快?

python - Pandas如何根据每组的长度和另一列的计数值计算按组结果

python - 如何在Python中比较2个数据帧而不比较空值?

python - google-app-engine-django 加载装置

django -/.platform/hooks/' : No such file or directory when deploying Django App to AWS Elastic Beanstalk

python - 在新窗口而不是内联显示图(以前的帖子没有回答)

python - 如何更改条形宽度,同时保持所有条形周围的间距均匀

python - 如何使用xlsxwriter写入没有数据框的excel文件

mysql - 安装 mysql python 时遇到问题,在 django 中找不到 mysqldb 模块

python - 如何将等高线图(matplotlib)转换为带标题的 FITS 格式?