如何在Python Dash应用的Plotly图表模式栏添加全屏图标
给Python Dash所有Plotly图表的模式栏添加全屏选项
直接通过注入自定义JS代码就能实现全局生效,不用逐个修改图表配置,下面是适配Dash环境的完整方案:
实现代码
import dash from dash import dcc, html import plotly.express as px app = dash.Dash(__name__) # 示例数据与图表 df = px.data.iris() sample_fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species") app.layout = html.Div([ dcc.Graph(figure=sample_fig, id="graph-1"), dcc.Graph(figure=sample_fig, id="graph-2"), # 注入自定义JS实现全屏按钮 html.Script(""" window.addEventListener('load', () => { // 定义全屏按钮的配置 const fullscreenBtn = { name: '全屏', icon: Plotly.Icons.fullscreen, click: (gd) => { const container = gd.getContainer(); if (!document.fullscreenElement) { container.requestFullscreen().catch(err => { console.error('全屏请求失败:', err); }); } else { document.exitFullscreen(); } } }; // 给已加载的图表添加按钮 document.querySelectorAll('.js-plotly-plot').forEach(plot => { const gd = plot.querySelector('.plot'); if (gd?._context) { const hasFullscreen = gd._context.config.modeBarButtonsToAdd?.some(btn => btn.name === '全屏'); if (!hasFullscreen) { gd._context.config.modeBarButtonsToAdd = [...(gd._context.config.modeBarButtonsToAdd || []), fullscreenBtn]; Plotly.react(gd, gd.data, gd.layout, gd._context.config); } } }); // 监听DOM变化,给动态生成的图表自动加按钮 const observer = new MutationObserver(mutations => { mutations.forEach(mutation => { mutation.addedNodes.forEach(node => { if (node.classList?.contains('js-plotly-plot')) { const gd = node.querySelector('.plot'); if (gd?._context) { const hasFullscreen = gd._context.config.modeBarButtonsToAdd?.some(btn => btn.name === '全屏'); if (!hasFullscreen) { gd._context.config.modeBarButtonsToAdd = [...(gd._context.config.modeBarButtonsToAdd || []), fullscreenBtn]; Plotly.react(gd, gd.data, gd.layout, gd._context.config); } } } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); }); """) ]) if __name__ == '__main__': app.run_server(debug=True)
关键细节
- 全局覆盖:不管是页面初始化时的图表,还是后续通过回调动态生成的图表,都会自动添加上全屏按钮,无需额外配置。
- 风格统一:使用Plotly内置的全屏图标,和原生模式栏按钮风格一致。
- 防重复注入:每次添加前检查按钮是否已存在,避免重复添加导致模式栏混乱。
单图表配置方案(可选)
如果只需要给特定图表加全屏按钮,可以直接在dcc.Graph的config参数里配置:
dcc.Graph( figure=sample_fig, config={ 'modeBarButtonsToAdd': [{ 'name': '全屏', 'icon': Plotly.Icons.fullscreen, 'click': (gd) => { const container = gd.getContainer(); document.fullscreenElement ? document.exitFullscreen() : container.requestFullscreen(); } }] } )
内容的提问来源于stack exchange,提问作者user23027270
相关产品推荐
相关产品推荐

