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

如何在Jupyter与Sphinx文档中实现Plotly图表全屏及表格滚动?

Plotly图表全屏弹窗与Sphinx文档表格滚动优化

一、Plotly图表全屏弹窗实现

Plotly.py自带便捷方式

Plotly.py生成的交互式图表默认自带全屏按钮,位于图表右上角工具栏(与下载、截图按钮并列,图标为全屏样式)。无论在Jupyter Notebook还是Sphinx渲染页面中,正常渲染Plotly图表后,用户点击该按钮即可直接切换至全屏模式,无需额外配置。

自定义全屏触发(Sphinx文档)

若需在图表外部添加自定义触发按钮(如页面内文本按钮),可借助Plotly.js API实现:

  1. 在Sphinx项目的_templates/layout.html中引入自定义JavaScript文件(或直接嵌入脚本)。
  2. 编写JS代码,通过图表ID调用全屏方法:
// 假设图表DOM元素ID为"plotly-chart"
document.getElementById('custom-fullscreen-btn').addEventListener('click', function() {
    Plotly.fullscreen(document.getElementById('plotly-chart'));
});

二、多列表格滚动模式实现

Plotly表格原生支持

使用plotly.graph_objects.Table生成的表格,当宽度超出容器时默认自动出现横向滚动条。若未生效,可在布局配置中显式设置容器样式:

import plotly.graph_objects as go

fig = go.Figure(data=[go.Table(
    header=dict(values=['列1', '列2', ..., '列N']),
    cells=dict(values=[data1, data2, ..., dataN])
)])

# 强制启用横向滚动的布局设置
fig.update_layout(
    autosize=True,
    margin=dict(l=0, r=0, t=0, b=0)
)
fig.write_html("table.html")  # 用于Sphinx嵌入

Sphinx文档全局优化方案

针对Sphinx页面中其他类型表格(如RST自动生成表格、第三方组件表格),可通过自定义CSS/JS实现全局滚动:

  1. 创建自定义CSS文件(_static/css/custom.css),添加滚动容器样式:
.scrollable-table-wrapper {
    overflow-x: auto;
    margin: 1.5em 0;
}
  1. 在Sphinx的conf.py中引入该CSS:
html_static_path = ['_static']
html_css_files = ['css/custom.css']
  1. 可选:添加JS自动识别宽表格并包裹容器(_static/js/custom.js):
document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('table').forEach(table => {
        const parentWidth = table.parentElement.offsetWidth;
        if (table.scrollWidth > parentWidth) {
            const wrapper = document.createElement('div');
            wrapper.className = 'scrollable-table-wrapper';
            table.parentNode.insertBefore(wrapper, table);
            wrapper.appendChild(table);
        }
    });
});
  1. 在conf.py中引入JS文件:
html_js_files = ['js/custom.js']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 04:39:34