我想使用plotly构建一个脱机应用程序以显示图形。我在后端使用python(flask),在前端使用HTML(javascript)。目前,我可以通过将图形数据作为JSON对象发送到前端并在前端本身使用plotly.js构建图形来绘制图形。但是我真正想要的是在服务器(后端即python)本身构建图形,然后以HTML显示数据。我已经遍历了在python中构建图形的绘图文档,但是我不知道如何将构建图形发送到前端进行显示:(有人可以帮我吗?PS:我想构建一个脱机应用程序更新了代码
$(window).resize(function() {
var divheight = $("#section").height();
var divwidth = $("#section").width();
var update = {
width:divwidth, // or any new width
height:divheight // " "
};
var arr = $('#section > div').get();
alert(arr[1]);
Plotly.relayout(arr[0], update);
}).resize();
});
我的建议是使用该plotly.offline
模块,该模块为您创建绘图的脱机版本。他们网站上的可打印API太可怕了(我们实际上不希望知道每个函数采用什么参数,会吗?),所以转到Github上的源代码要好得多。
如果你看看plotly源代码,你可以看到,offline.plot
函数有一个kwarg的output_type
,这是两种'file'
或'div'
:
https://github.com/plotly/plotly.py/blob/master/plotly/offline/offline.py
因此,您可以执行以下操作:
from plotly.offline import plot
from plotly.graph_objs import Scatter
my_plot_div = plot([Scatter(x=[1, 2, 3], y=[3, 1, 6])], output_type='div')
这将为您提供代码(包装在<div>
标签中)以直接插入HTML。可能不是最有效的解决方案(因为我很确定它也嵌入了相关的d3代码,可以将其缓存以重复请求),但是它是自包含的。
要将您的div使用Flask插入html代码中,您需要做一些事情。
在结果页面的html模板文件中,为绘图代码创建一个占位符。Flask使用Jinja模板引擎,因此如下所示:
<body>
....some html...
{{ div_placeholder }}
...more html...
</body>
在Flaskviews.py
文件中,您需要使用在div_placeholder
变量中插入了绘图代码来呈现模板:
from plotly.offline import plot
from plotly.graph_objs import Scatter
from flask import Markup
...other imports....
@app.route('/results', methods=['GET', 'POST'])
def results():
error = None
if request.method == 'POST':
my_plot_div = plot([Scatter(x=[1, 2, 3], y=[3, 1, 6])], output_type='div')
return render_template('results.html',
div_placeholder=Markup(my_plot_div)
)
# If user tries to get to page directly, redirect to submission page
elif request.method == "GET":
return redirect(url_for('submission', error=error))
显然是YMMV,但这应该说明基本原理。请注意,您可能会收到使用POST数据获得的用户请求,而创建plotly图需要处理这些数据。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句