【问题标题】:Embedding a Plotly chart in a Django template在 Django 模板中嵌入 Plotly 图表
【发布时间】:2016-08-19 04:30:22
【问题描述】:

我正在尝试在 Django html 模板中嵌入一个绘图饼图。当图表以“在线模式”(即 html sn-p 存储在 plotly 服务器上)而不是“离线模式”(即 html 存储在本地时)时,这可以正常工作。在后一种情况下,图表不会出现。我希望能够将 html 存储在我的本地服务器上并从那里嵌入绘图。

这是有效的:

import plotly.plotly as py
import plotly.graph_objs as go
labels = [1,2,3,4]
values = [10,20,30,40]
ndata = 100
fig = {
    'data': [{'labels': labels,
          'values': values,
          'type': 'pie',
          'textposition':"none",
          'textinfo':"percent",
          'textfont':{'size':'12'},
          'showlegend':'false'}],
    'layout': {'title': 'Total:'+str(ndata),
           'showlegend':'false',
           'height':'200',
           'width':'200',
           'autosize':'false',
           'margin':{'t':'50','l':'75','r':'0','b':'10'},
           'separators':'.,'}
}
plotly_url = py.plot(fig, filename='myfile', auto_open=False)
pie_url = '<iframe width="200" height="200" frameborder="0" seamless="seamless" scrolling="no" src='+plotly_url+'.embed?width=200&height=200&link=false&showlegend=false></iframe>'

注意 pie_url 在 Django 的 Http 渲染请求中作为字符串传递。模板使用 | 安全标记将字符串解释为 html,即 {{ pie_url|safe }}。

这是不起作用的位:

from plotly.offline import download_plotlyjs, plot
import plotly.graph_objs as go
labels = [1,2,3,4]
values = [10,20,30,40]
ndata = 100
fig = {
    'data': [{'labels': labels,
          'values': values,
          'type': 'pie',
          'textposition':"none",
          'textinfo':"percent",
          'textfont':{'size':'12'},
          'showlegend':'false'}],
    'layout': {'title': 'Total:'+str(ndata),
           'showlegend':'false',
           'height':'200',
           'width':'200',
           'autosize':'false',
           'margin':{'t':'50','l':'75','r':'0','b':'10'},
           'separators':'.,'}
}
plotly_url = plot(fig, filename='file:///home/website/pie.html', auto_open=False)
pie_url = '''<iframe width="200" height="200" frameborder="0" seamless="seamless" scrolling="no" src=\"'''+plotly_url+'''.embed?width=200&height=200&link=false&showlegend=false\"></iframe>'''

任何建议将不胜感激。

【问题讨论】:

  • 你能把它输出到一个.html文件吗?
  • 嗨,是的,html 文件已生成。但是当 Django 渲染它时它并没有显示出来(这是原始帖子中的 pie_url 行。)
  • 将保存到 pie_url 中的字符串包裹在三个 ' 而不是单个 ' 之间是否正确?

标签: python django plotly


【解决方案1】:

您可以将图形的 html 部分作为字符串返回,而不是将 html 写入文件。例如,使用基于类的 TemplateView:

编辑:使用最新(截至 2021/08 年)版本的 plotly 的更新。模板不需要任何更改。

import plotly.graph_objects as go

class Graph(TemplateView):
    template_name = 'graph.html'

    def get_context_data(self, **kwargs):
        context = super(Graph, self).get_context_data(**kwargs)

        x = [-2,0,4,6,7]
        y = [q**2-q+3 for q in x]
        trace1 = go.Scatter(x=x, y=y, marker={'color': 'red', 'symbol': 104, 'size': "10"},
                            mode="lines",  name='1st Trace')

        layout=go.Layout(title="Meine Daten", xaxis={'title':'x1'}, yaxis={'title':'x2'})
        figure=go.Figure(data=['trace1'],layout=layout)

        context['graph'] = figure.to_html()

        return context

这是原始代码:

import plotly.offline as opy
import plotly.graph_objs as go

class Graph(TemplateView):
    template_name = 'graph.html'

    def get_context_data(self, **kwargs):
        context = super(Graph, self).get_context_data(**kwargs)

        x = [-2,0,4,6,7]
        y = [q**2-q+3 for q in x]
        trace1 = go.Scatter(x=x, y=y, marker={'color': 'red', 'symbol': 104, 'size': "10"},
                            mode="lines",  name='1st Trace')

        data=go.Data([trace1])
        layout=go.Layout(title="Meine Daten", xaxis={'title':'x1'}, yaxis={'title':'x2'})
        figure=go.Figure(data=data,layout=layout)
        div = opy.plot(figure, auto_open=False, output_type='div')

        context['graph'] = div

        return context

和模板:

{% if graph %}
<div style="width:600;height:500">
{{ graph|safe }}
</div>
{% endif %}

【讨论】:

  • 你可以把它放在你的视图中来渲染这个上下文g = Graph()context = g.get_context_data()return render(request, 'app/stats.html', context)编辑:直接在url中使用TemplateViewsdocs.djangoproject.com/en/1.10/ref/class-based-views/base/…
  • 对于所有不熟悉基于类的视图的人,要使代码正常工作,请记住添加 from django.views.generic import TemplateView。另外,请阅读 Naman 指出的文档
【解决方案2】:

plotly 有一些更新,其中一些适用于 plotly 4+

  • Plotly is offline by default now

    注意:使用 plotly.py 不需要互联网连接、帐户或付款。 在版本 4 之前,此库可以在“在线”或“离线”模式下运行。该文档倾向于强调在线模式,其中图表被发布到 Chart Studio Web 服务。在版本 4 中,所有“在线”功能都从 plotly 包中删除,现在可作为单独的可选图表工作室包(见下文)。 plotly.py 版本 4 仅“离线”,不包含任何将图形或数据上传到云服务的功能。

  • 数字现在具有to_html 函数

这允许您执行以下操作以离线嵌入图表:

graph = fig.to_html(full_html=False, default_height=500, default_width=700)
context = {'graph': graph}
response = render(request, 'graph.html', context)

graph.html 你可以这样做:

{% if graph %}
{{ graph|safe }}
{% else %}
<p>No graph was provided.</p>
{% endif %}

【讨论】:

    【解决方案3】:

    假设您绘制图形的代码,即

    from plotly.offline import download_plotlyjs, plot
    import plotly.graph_objs as go
    labels = [1,2,3,4]
    values = [10,20,30,40]
    ndata = 100
    fig = {
        'data': [{'labels': labels,
              'values': values,
              'type': 'pie',
              'textposition':"none",
              'textinfo':"percent",
              'textfont':{'size':'12'},
              'showlegend':'false'}],
        'layout': {'title': 'Total:'+str(ndata),
               'showlegend':'false',
               'height':'200',
               'width':'200',
               'autosize':'false',
               'margin':{'t':'50','l':'75','r':'0','b':'10'},
               'separators':'.,'}
    }
    plotly_url = plot(fig, filename='file:///home/website/pie.html', auto_open=False)
    pie_url = '''<iframe width="200" height="200" frameborder="0" seamless="seamless" scrolling="no" src=\"'''+plotly_url+'''.embed?width=200&height=200&link=false&showlegend=false\"></iframe>'''
    

    是一个名为graph_function() 的函数。在那个里面,只是替换

    plotly_url = plot(fig, filename='file:///home/website/pie.html', auto_open=False)
    pie_url = '''<iframe width="200" height="200" frameborder="0" seamless="seamless" scrolling="no" src=\"'''+plotly_url+'''.embed?width=200&height=200&link=false&showlegend=false\"></iframe>'''
    

    plt_div = plotly.offline.plot(fig, output_type='div')
    
    return plt_div
    

    然后在你的views.py中:

    def graph_view(request):
        my_graph=graph_function()
        context={'graph':my_graph}
        return render(request, 'my_template.html', context_dict)
    

    然后在您的模板中:

    {% if graph %}
    {{ graph|safe }}
    {% else %}
    <p>No graph was provided.</p>
    {% endif %}
    

    【讨论】:

      猜你喜欢
      • 2013-07-10
      • 2023-03-02
      • 1970-01-01
      • 2017-11-06
      • 1970-01-01
      • 1970-01-01
      • 2023-01-17
      • 2014-01-15
      • 1970-01-01
      相关资源
      最近更新 更多