django - Django 中的 Plotly 和袖扣
问题描述
我目前正在试验如何在我的 django 模板中显示图表。通过将绘图转换为图像然后将其显示在模板中,我取得了一点成功。但这种方案不适用于 Plotly 和 Cufflinks 等交互式图形。
如何将 Plotly 和 Cufflinks 嵌入到我的 django 模板中,以便我的图表具有交互性?
解决方案
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>
推荐阅读
- python - Python pyqt5使settooltip的字体与按钮字体不同
- regex - 预读/回顾与捕获组
- python - NLP 多类分类器 loss 上不去
- docker - 无法使用 VS 2019 在 Linux 容器中运行 ASP.NET Core
- python - 将 tensorflow BERT 检查点转换为 pytorch 时出错
- python - 我可以在matplotlib中显示没有科学计数法的图片像素值吗
- reactjs - 在 useEffect 挂钩中进行的异步调用的测试结果
- python - 如何重塑 ndarray,特别是简单的方法 ro (25,25) 到 (1,1)?
- angularjs - 如何在选中复选框时将更改标签变为可见并在未选中时隐藏?
- javascript - 使用 Pre-ES6 语法的自定义元素