django中的Plotly和Cufflinks

问题描述 投票:1回答:1

我目前正在尝试如何在我的django模板中显示图表。通过将图转换为图像然后将其显示在模板中,我获得了一些成功。但是这种方案不适合像Plotly和Cufflinks这样的交互式图形。

如何将Plotly和Cufflinks嵌入到我的django模板中,以便我的图形将是交互式的?

django plotly
1个回答
1
投票

plotly.offline.plot有一个选项output_type='div',它使得绘图函数只返回一个包含情节html的div。

plotly.offline.plot(data, include_plotlyjs=False, output_type='div')

您可以将此div存储在变量中,并将其传递给模板。

下面是一个最小的工作示例。请注意,我们在模板文件的标题中导入plotly.js,并且我们使用safe过滤器。

view.朋友

from django.views.generic import TemplateView
import plotly.offline as py
import plotly.graph_objs as go
import numpy as np


class IndexView(TemplateView):
    template_name = "plots/index.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['plot'] = examplePlot()
        return context


def examplePlot():
    # Makes a simple plotly plot, and returns html to be included in template.
    x = np.linspace(0, 12.56, 41)
    y = np.sin(x)
    y2 = np.sin(1.2*x)

    data = [
        go.Scatter(
            name = 'Sin(x)',
            x=x,
            y=y,
        ),

        go.Scatter(
            name = 'Sin(1.2x)',
            x=x,
            y=y2,
        ),
    ]

    layout = go.Layout(
        xaxis=dict(
            title='x'
        ),

        yaxis=dict(
            title='Value',
            hoverformat = '.2f'
        ),
    )

    fig = go.Figure(data=data, layout=layout)
    plot_div = py.plot(fig, include_plotlyjs=False, output_type='div')

    return plot_div

图/ index.html的

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Plotly test</title>
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
  </head>
  <body>
    {{plot|safe}}
  </body>
</html>

这是结果的截图,它是交互式的。 enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.