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

如何在Python中移除Quarto上Plotly表格与图号间的空白

解决Quarto中Plotly表格与图号的空白问题

表格与图号之间的空白

如上图所示,Plotly表格和Quarto生成的图号之间存在多余空白,可通过以下两种方法消除:

方法1:调整Plotly图表的边距

Plotly默认会给图表添加顶部边距,这是空白的主要来源。在生成图表后,通过update_layout将顶部边距设为0即可:

修改代码,在fig.show()前添加边距设置:

fig.update_layout(margin=dict(t=0, b=0, l=0, r=0))

完整代码:

#| echo: false
#| label: fig-wealthy
#| fig-cap: "Wealthy Indicators"

import plotly.graph_objects as go

values = [
    [
        'Income Ratio', 
        '% Children in Poverty', 
        'Unemployment Rate'
    ],
    [
        'Ratio of household income at the 80th percentile to income at the 20th percentile',
        'Percentage of children (under age 18) living in poverty',
        'Percentage of population ages 16+ who are unemployed'
    ]
]


fig = go.Figure(data=[go.Table(
  columnorder = [1,2],
  columnwidth = [25,60],
  header = dict(
    values = [
        ['<b>Indicator</b>'],
        ['<b>Description</b>']
    ],
    line_color='darkslategray',
    fill_color=['rgb(241, 241, 241)', 'rgb(241, 241, 241)'],
    align=['center','center'],
    font=dict(color='rgb(22,74,88)', size=12),
    height=20
  ),
  cells=dict(
    values=values,
    line_color='darkslategray',
    fill=dict(color=['white', 'white']),
    align=['left', 'left'],
    font=dict(color='black', size=12),
    height=30)
)])

# 消除图表顶部空白
fig.update_layout(margin=dict(t=0, b=0, l=0, r=0))
fig.show()

方法2:自定义Quarto的CSS样式

如果方法1仍有残留空白,可在文档开头添加CSS代码,直接控制figure容器的间距:

<style>
figure {
  margin-top: 0;
  padding-top: 0;
}
.plotly.html-widget {
  margin-top: 0 !important;
}
</style>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 20:05:33