如何在Django上使用Plotly创建图表?

Hir*_*uri 12 python django plotly

我想创建一个仪表板,我可以使用该库分析一下我的模型数据(文章)plotly.

Plotly条形图没有显示在我的模板上,我想知道我是否做错了,因为下面的代码没有错误:

models.py

from django.db import models
from django.contrib.auth.models import User
import plotly.plotly as py
import plotly.graph_objs as go

class Article(models.Model):
    user = models.ForeignKey(User, default='1')
    titre = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=40)
    likes = models.ManyToManyField(User, related_name="likes")

    def __str__(self):
        return self.titre

    @property
    def article_chart(self):
        data = [
            go.Bar(
                x=[self.titre], #title of the article
                y=[self.likes.count()] #number of likes on an article
            )
        ]
        plot_url = py.plot(data, filename='basic-bar')

        return plot_url
Run Code Online (Sandbox Code Playgroud)

dashboard.html

<div>{{ article.article_chart }}</div>
Run Code Online (Sandbox Code Playgroud)

为什么条形图不可见?有什么建议吗?

小智 11

的结果

py.plot(data, filename='basic-bar')
Run Code Online (Sandbox Code Playgroud)

是生成脱机HTML文件并返回此文件的本地URL

例如file:///your_project_pwd/temp-plot.html

如果你想在Django框架中渲染它,你需要

  • <iframe>在Django设置中使用和重新构建您的文件夹

要么

  • 使用plotly.offline方法生成带有输入的HTML代码 data

我尝试过一个例子:

figure_or_data = [Scatter(x=[1, 2, 3], y=[3, 1, 6])]

plot_html = plot_html, plotdivid, width, height = _plot_html(
    figure_or_data, True, 'test', True,
    '100%', '100%')

resize_script = ''
if width == '100%' or height == '100%':
    resize_script = (
        ''
        '<script type="text/javascript">'
        'window.removeEventListener("resize");'
        'window.addEventListener("resize", function(){{'
        'Plotly.Plots.resize(document.getElementById("{id}"));}});'
        '</script>'
    ).format(id=plotdivid)

html = ''.join([
            plot_html,
            resize_script])

return render(request, 'dashboard.html', {'html': html,})
Run Code Online (Sandbox Code Playgroud)