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

如何缩小Plotly.js中标题与环形图的间距?

问题:缩小Plotly.js环形图与标题的间距

我用Plotly.js实现了环形图,想要缩小标题和环形图之间的间距,尝试在margin对象中添加pad:0但没有效果,也没找到title对象里的相关配置属性,请问有没有可用的属性实现这个需求?

当前代码

const donutData = [
  {
    values: [2, 98],
    labels: ['', ''],
    sort: false,
    marker: {
      colors: ['#0099cc', '#535353'],
    },
    name: '',
    hoverinfo: 'none',
    textfont: {
      size: [16, 1],
      color: ['#ffffff', '#535353'],
      fill: ['#ffffff', '#535353'],
    },
    hole: 0.7,
    insidetextorientation: 'none',
    type: 'pie',
    textposition: 'none',
    automargin: true,
  },
];
const layout = {
  paper_bgcolor: '#262626',
  plot_bgcolor: '#262626',
  autosize: true,
  margin: { t: 100, b: 10, l: 0, r: 0 },
  font: {
    color: '#fff',
    family: 'Roboto',
    size: 18,
  },
  showlegend: false,
  width: 500,
  height: 500,
  title: {
    text: `donut`,
  },
  annotations: [
    {
      font: {
        size: 60,
      },
      showarrow: false,
      text: `30%`,
    },
  ],
};

解决方法

可以通过以下两种方式调整间距:

  1. 缩小顶部边距
    你当前的margin.t设为100,给标题上方留了过多空白,直接减小这个值就能拉近标题和图表的距离,比如改成50:

    margin: { t: 50, b: 10, l: 0, r: 0 }
    
  2. 配置标题内边距与位置
    在title对象里添加pad属性去除标题底部的内边距,还可以通过y属性精细控制标题的垂直位置(取值范围0-1,1对应容器顶部,0对应底部):

    title: {
      text: `donut`,
      pad: { b: 0 }, // 去掉标题底部内边距
      y: 0.9 // 让标题更靠下,靠近图表
    }
    

修改后的完整layout示例

const layout = {
  paper_bgcolor: '#262626',
  plot_bgcolor: '#262626',
  autosize: true,
  margin: { t: 50, b: 10, l: 0, r: 0 }, // 缩小顶部边距
  font: {
    color: '#fff',
    family: 'Roboto',
    size: 18,
  },
  showlegend: false,
  width: 500,
  height: 500,
  title: {
    text: `donut`,
    pad: { b: 0 }, // 移除标题底部内边距
    y: 0.9 // 调整标题垂直位置
  },
  annotations: [
    {
      font: {
        size: 60,
      },
      showarrow: false,
      text: `30%`,
    },
  ],
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 07:10:12