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

ChartJS环形图(Doughnut Chart)内边距与尺寸控制问题

ChartJS环形图尺寸与位置控制难题

我在调整ChartJS环形图(Doughnut Chart)的尺寸和位置时卡壳了——图表自动添加了大量内边距,没法和所在行的其他元素保持一致的垂直空间占用。查了一堆相关问题的解法,都不管用。

问题截图:
问题截图

当前使用的代码:

<Row>          
  <Col className="mx-auto text-dark text-md-left">
    <Row>
      <Col>
        <img className="profilepics mb-3" src={photo} alt={teamMemberName} />
        <p>
          <strong>Date of Hire:</strong> {hiredate}
        </p>
        <p>
          <strong>Birthday:</strong> {birthday}
        </p>
      </Col>
      <Col>
        <Doughnut
          data={{
            labels: [
              'Billable Hours',
              'Non-Billable Hours'
            ],
            datasets: [{
              label: 'Billable Percentage',
              radius: "50%",
              innerRadius: "75",
              data: [renderBillableHours, (renderTotalHours - renderBillableHours)],
              backgroundColor: [
                'rgb(10, 120, 10)',
                'rgb(190, 10, 10)',
              ],
              hoverOffset: 4
            }]
          }}
          options={{
            maintainAspectRation: false,
            layout: {
              autoPadding: false,
            },
            plugins: {
              legend: {
                display: false
              }
            }
          }}
        />
      </Col>
    </Row>
  </Col>
  <Col className="mx-auto text-dark text-md-right">
    <h3 className="display-4">Hello, {teamMemberName}!</h3>
    <h5 className="pt-3">
      Current Billable Amount: $
      {renderBillableAmount.toLocaleString("en", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      })}
    </h5>
    <p>
      Billable Goal: ${goal.toLocaleString()} | Difference: $
      {(renderDifference).toLocaleString("en", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      })}
    </p>
  </Col>
</Row>

几个关键修正点(可能你之前没注意到):

  • 拼写错误导致配置失效:options里的maintainAspectRation拼错了,正确写法是maintainAspectRatio——这个错误会让禁止保持宽高比的设置不生效,图表仍按默认比例生成,进而出现多余内边距。
  • 手动强制清零内边距:在layout里不仅要关闭autoPadding,还要显式设置所有方向的padding为0:
    layout: {
      autoPadding: false,
      padding: { top: 0, right: 0, bottom: 0, left: 0 }
    }
    
  • 给图表容器设固定高度:给放置<Doughnut>的<Col>或外层容器添加固定高度,比如用CSS类:
    .chart-col {
      height: 220px; /* 参考同行元素的高度调整数值 */
    }
    
    然后给对应的<Col>加上className="chart-col",强制图表容器高度和其他元素对齐。
  • 修正innerRadius的单位:innerRadius: "75"未指定单位,建议改成"75%",避免尺寸计算异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 18:57:06