dan*_*dhi 5 html python plotly
我想使用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();
});
Run Code Online (Sandbox Code Playgroud)
And*_*Guy 15
我的建议是使用该plotly.offline模块,为您创建一个离线版本的图.在他们的网站上的情节API是可怕的(我们实际上不想知道每个函数采用什么参数,我们会??),更好地转向Github上的源代码.
如果您查看了图形源代码,您可以看到该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')
Run Code Online (Sandbox Code Playgroud)
这将为您提供<div>直接插入HTML 的代码(包含在标签中).也许不是最有效的解决方案(因为我很确定它也嵌入了相关的d3代码,可能只是为重复的请求缓存),但它是自包含的.
要使用Flask将div插入到html代码中,您需要做一些事情.
在结果页面的html模板文件中,为您的绘图代码创建一个占位符.Flask使用Jinja模板引擎,所以这看起来像:
<body>
....some html...
{{ div_placeholder }}
...more html...
</body>
Run Code Online (Sandbox Code Playgroud)
在Flask views.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))
Run Code Online (Sandbox Code Playgroud)
显然是YMMV,但那应该说明基本原理.请注意,您可能会使用POST数据获取用户请求,您需要处理这些数据以创建绘图图形.
您可以使用以下.to_html()方法:
import plotly.express as px
fig = px.scatter(x=[0, 1, 2, 3, 4], y=[0, 1, 4, 9, 16])
div = fig.to_html(full_html=False) # Get the <div> to send to your frontend and embed in an html page
Run Code Online (Sandbox Code Playgroud)