You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask中带下拉菜单的Plotly离线图表显示空白问题求助

解决Flask中带下拉菜单的Plotly图表空白问题

我帮你排查了代码里的问题,核心原因是Plotly.js版本过低导致的,另外还有一点参数优化可以让功能更稳定,下面是具体的解决方案:

问题根源

你使用的是非常老旧的Plotly基础版(plotly-basic.js),这个版本不支持updatemenus中通过restyle方法切换图表类型的特性,渲染带交互控件的图表时直接失败,最终页面显示空白。

修复步骤

1. 更新前端的Plotly.js CDN链接

把HTML模板里旧的Plotly.js替换成最新的完整版CDN,新版本支持所有交互控件特性:

<!-- 替换掉旧的plotly-basic.js -->
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>

2. 优化后端updatemenus的参数(可选,但更严谨)

原来的按钮参数没有指定要修改的trace索引,虽然新版本能默认生效,但明确指定索引可以避免多trace场景下的混乱:

buttons=list([
    dict(
        args=[{'type': 'surface'}, [0]],  # 指定修改第0个trace的类型
        label='3D Surface',
        method='restyle'
    ),
    dict(
        args=[{'type': 'heatmap'}, [0]],
        label='Heatmap',
        method='restyle'
    )
])

3. 完整修改后的代码

后端Flask代码(仅修改updatemenus部分)

from flask import Flask,render_template,url_for
import plotly.graph_objs as go
import pandas as pd
import plotly
import json

app = Flask(__name__)

@app.route('/')
def dashboards():
    # 读取数据
    df = pd.read_csv('raw.githubusercontent.com/plotly/datasets/master/volcano.csv')
    data = [go.Surface(z=df.values.tolist(), colorscale='Viridis')]

    layout = go.Layout(
        width=800,
        height=900,
        autosize=False,
        margin=dict(t=0, b=0, l=0, r=0),
        scene=dict(
            xaxis=dict(
                gridcolor='rgb(255, 255, 255)',
                zerolinecolor='rgb(255, 255, 255)',
                showbackground=True,
                backgroundcolor='rgb(230, 230,230)'
            ),
            yaxis=dict(
                gridcolor='rgb(255, 255, 255)',
                zerolinecolor='rgb(255, 255, 255)',
                showbackground=True,
                backgroundcolor='rgb(230, 230, 230)'
            ),
            zaxis=dict(
                gridcolor='rgb(255, 255, 255)',
                zerolinecolor='rgb(255, 255, 255)',
                showbackground=True,
                backgroundcolor='rgb(230, 230,230)'
            ),
            aspectratio=dict(x=1, y=1, z=0.7),
            aspectmode='manual'
        )
    )

    updatemenus = list([
        dict(
            buttons=list([
                dict(
                    args=[{'type': 'surface'}, [0]],
                    label='3D Surface',
                    method='restyle'
                ),
                dict(
                    args=[{'type': 'heatmap'}, [0]],
                    label='Heatmap',
                    method='restyle'
                )
            ]),
            direction='down',
            pad={'r': 10, 't': 10},
            showactive=True,
            x=0.1,
            xanchor='left',
            y=1.1,
            yanchor='top'
        ),
    ])

    annotations = list([
        dict(text='Trace type:', x=0, y=1.085, yref='paper', align='left', showarrow=False)
    ])

    layout['updatemenus'] = updatemenus
    layout['annotations'] = annotations

    fig = dict(data=data, layout=layout)
    # 转换为JSON格式
    graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
    # 渲染模板
    return render_template('dashboard.html', graphJSON=graphJSON)

if __name__ == '__main__':
    app.run()

HTML模板代码(更新Plotly.js链接)

<!doctype html>
<html>
<head>
</head>
<body>
    <h3>Fruit Plot</h3>
    <div id="graph-0"></div>
</body>
<footer>
    <!-- 保留原有依赖,新版本Plotly兼容旧版D3和jQuery -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
    <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
    <!-- 更新为最新Plotly.js -->
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    <script type="text/javascript">
        var fig = {{graphJSON | safe}};
        Plotly.plot("graph-0", fig.data, fig.layout);
    </script>
</footer>
</html>

验证效果

启动Flask应用后,访问首页就能看到带下拉菜单的3D曲面图,点击下拉菜单可以流畅切换为热力图,页面不会再出现空白。

内容的提问来源于stack exchange,提问作者tekstar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:41:05