首页 > 解决方案 > Django 中的 Plotly 和袖扣

问题描述

我目前正在试验如何在我的 django 模板中显示图表。通过将绘图转换为图像然后将其显示在模板中,我取得了一点成功。但这种方案不适用于 Plotly 和 Cufflinks 等交互式图形。

如何将 Plotly 和 Cufflinks 嵌入到我的 django 模板中,以便我的图表具有交互性?

标签: djangoplotly

解决方案


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

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

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

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

视图.py

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>

这是结果的屏幕截图,它是交互式的。 在此处输入图像描述


推荐阅读