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

如何让图表图例垂直居中?为底部图例上方添加间距

解决Chart.js底部图例上方间距不足的问题

当图例设置为底部位置时,仅通过插件增加图例height会导致新增空间从图例底部向下延伸,无法在图例与图表主体之间留出预期空隙。要实现上方加间距的效果,需同时调整图例的位置,而非仅修改高度。

修改后的自定义插件代码

export const legendMargin: Plugin = {
  id: "legendMargin",
  afterInit: (chart: Chart) => {
    const originalFit = chart.legend!.fit;
    chart.legend!.fit = function fit() {
      // 执行原始布局逻辑,获取图例默认位置与高度
      originalFit.call(this);
      
      const extraTopMargin = 140;
      // 扩展图例高度,避免内容截断
      this.height += extraTopMargin;
      // 下移图例位置,让新增空间出现在图例上方(画布Y轴向下递增,top值增大则整体下移)
      this.top += extraTopMargin;
    };
  },
};

代码说明

  1. 保留原始fit方法的执行,确保图例基础布局逻辑正常运行。
  2. 定义需要添加的上方间距值extraTopMargin。
  3. 扩展图例高度,防止图例内容因位置调整被截断。
  4. 修改top属性:由于Chart.js画布Y轴向下递增,增大top值会让图例整体向下移动,从而在图例与图表主体之间留出设置的间距空间。

更简便的替代方案

如果仅需在图例与图表之间添加间距,无需自定义插件,直接调整图表布局的底部内边距即可:

{
  "type": "doughnut",
  "plugins": [customCanvasBg],
  "options": {
    "layout": {
      "padding": {
        "bottom": 140 // 为图例预留上方空间
      }
    },
    "plugins": {
      "legend": {
        "display": true,
        "position": "bottom",
        "labels": {
          "padding": 4,
          "pointStyleWidth": 40,
          "pointStyle": "rectRounded",
          "usePointStyle": true,
          "color": "#504f6b",
          "font": {
            "size": 16,
            "weight": 600,
            "family": "Inter"
          }
        }
      }
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 05:44:51