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

14

我正在尝试创建一个仪表板,使用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

仪表板.html

<div>{{ article.article_chart }}</div>
为什么条形图不可见?有什么建议吗?

article_chartArticle 的一个属性,因此您需要在模板中引用它,如 {{ article.article_chart }} - Franey
2个回答

13

的结果

py.plot(data, filename='basic-bar')

目的是生成一个离线HTML文件并返回该文件的本地URL。

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

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

  • 使用<iframe>标签,并在Django设置中重新组织你的文件夹结构。

或者

  • 使用plotly.offline方法来生成具有你的输入数据的HTML代码

这里有一个我尝试过的例子:

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,})

3

以上回答非常有用,实际上我正在寻找父级改变大小的情况,我正在使用Angular,并使用以下代码来实现调整大小,我遇到了类似的问题,这行代码非常有用。

<div class="col-lg-12" ng-if="showME" style="padding:0px">
   <div id="graphPlot" ng-bind-html="myHTML"></div>
</div>

图表将通过变量myHTML插入。

我所做的就是观察父元素的调整大小,使用jquery仅获取div id并将其传递给plotly,然后它便可以正常工作。

$scope.$on("angular-resizable.resizeEnd", function (event, args){
        Plotly.Plots.resize(document.getElementById($('#graphPlot').children().eq(0).attr("id")));
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接