使用 python 绘制图形并使用 HTML 显示它

Plotting graph using python and dispaying it using HTML

我想使用 plotly 构建一个离线应用程序来显示图表。我在后端使用 python(flask),在前端使用 HTML(javascript)。目前,我可以通过将图形数据作为 JSON 对象发送到前端并在前端本身使用 plotly.js 构建图形来绘制图形。但我真正想要的是在服务器(后端即 python)端本身构建图形,然后在 HTML 中显示数据。我已经浏览了在 python 中构建图表的 plotly 文档,但我不知道如何将构建图表发送到前端进行显示:( 有人可以帮我吗? 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 函数接受了 output_type 的 kwarg,它是 '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 代码,可以为重复请求缓存),但它是独立的。

要使用 Flask 将 div 插入到 html 代码中,您需要做一些事情。

在结果页面的 html 模板文件中,为绘图代码创建一个占位符。 Flask 使用 Jinja 模板引擎,所以它看起来像:

<body>
....some html...

{{ div_placeholder }}

...more html...
</body>

在您的 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))

显然是YMMV,但那应该能说明基本原理。请注意,您可能会收到使用 POST 数据的用户请求,您需要处理这些数据才能创建绘图。

您可以使用.to_html()方法:

https://plot.ly/python-api-reference/generated/plotly.graph_objects.Figure.html#plotly.graph_objects.Figure.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