简体   繁体   English

在Flask发送883276440288图为json从python到javascript

[英]Send Plotly figure as json from python to javascript in Flask

I have this code that generates a figure as a json object:我有这段代码生成一个数字作为 json object:

linear_regression_fig = go.Figure()
    # plot predicted values
    linear_regression_fig.add_trace(go.Scatter(
        x=group_by_df['day'].map(dt.datetime.fromordinal),
        y=group_by_df['predicted']))
    # plot actual values
    linear_regression_fig.add_trace(go.Scatter(
        x=group_by_df['day'].map(dt.datetime.fromordinal),
        y=group_by_df[sensor_name],
        name=('Actual values'),
        mode='lines+markers'))

    linear_regression_fig.update_layout(
        height=700,
        font=dict(color="grey"),
        paper_bgcolor='rgba(0,0,0,0)',
        title=('Linear Regression for ') + (sensor_name),
        yaxis_title=(sensor_name),
        xaxis_title=('Day'),
        showlegend=True)
    linear_regression_json = json.dumps(linear_regression_fig, cls=plotly.utils.PlotlyJSONEncoder)

And here I want to display the figure inside a div in the html page:在这里,我想在 html 页面的一个 div 中显示图形:


<div class="chart" id="pred_plot">
    <script>
        var graphs = {
        {
            prediction_plot_py | safe
        }
        }
        ;
        Plotly.plot('pred_plot', graphs, {});
    </script>
</div>

But I get this error "identifier or string literal or numeric literal expected" in the javascript section.但是我在 javascript 部分收到此错误“应为标识符或字符串文字或数字文字”。 How can I solve this?我该如何解决这个问题? I mention that this code worked at the beginning of summer and the plot was displayed correctly.我提到这段代码在夏初有效,plot 正确显示。

This is invalid JSON:这是无效的 JSON:

 var graphs = {
        {
            prediction_plot_py | safe
        }
        }

Additionally, you put an empty object as a parameter to Plotly.plot(), which I am not sure if you intended.此外,您将一个空的 object 作为参数传递给 Plotly.plot(),我不确定您是否有意这样做。 Proper JSON looks like this:正确的 JSON 看起来像这样:

var graphs = {
    {
        prediction_plot_py: "safe",
        example: "test"
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM