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

如何通过react-chartjs-2与chart.js将雷达图尺寸缩小一半?

React-Chartjs-2雷达图尺寸缩小解决方案

直接给容器加样式没效果,核心原因是Chart.js默认会维护固定宽高比,忽略容器的高度设置。下面是几种可行的解决方法:

方法1:容器样式 + 关闭宽高比维护

给容器设置目标尺寸(比如原尺寸的50%),同时在Chart配置里关闭maintainAspectRatio,让图表自适应容器:

import { Radar } from 'react-chartjs-2';
import { Chart as ChartJS, RadialLinearScale, PointElement, LineElement, Filler, Tooltip, Legend } from 'chart.js';

ChartJS.register(RadialLinearScale, PointElement, LineElement, Filler, Tooltip, Legend);

const data = {
  labels: ['维度1', '维度2', '维度3', '维度4', '维度5'],
  datasets: [
    {
      label: '数据集',
      data: [80, 90, 70, 60, 85],
      backgroundColor: 'rgba(255, 99, 132, 0.2)',
      borderColor: 'rgba(255, 99, 132, 1)',
      pointBackgroundColor: 'rgba(255, 99, 132, 1)',
      pointBorderColor: '#fff',
    },
  ],
};

const options = {
  maintainAspectRatio: false, // 关键:关闭默认宽高比锁定
  scales: {
    r: {
      suggestedMin: 0,
      suggestedMax: 100,
    },
  },
};

function RadarChart() {
  return (
    // 这里设置容器为原尺寸的50%,比如原宽800就设400,或直接用百分比
    <div style={{ width: '50%', height: '400px' }}>
      <Radar data={data} options={options} />
    </div>
  );
}

export default RadarChart;

方法2:直接给Chart组件设尺寸

不想折腾容器的话,直接给Radar组件传入width和height属性,同样配合maintainAspectRatio: false:

// 保持上面的data和options不变
<Radar data={data} options={options} width={400} height={400} />

方法3:自定义宽高比(可选)

如果需要保留宽高比,只想按比例缩小,可以开启maintainAspectRatio,设置aspectRatio,再给容器设宽度为50%:

const options = {
  responsive: true,
  aspectRatio: 1, // 设置为正方形,按需调整
  maintainAspectRatio: true,
  // 其他配置...
};

// 容器只设宽度,高度由宽高比自动计算
<div style={{ width: '50%' }}>
  <Radar data={data} options={options} />
</div>

注意:如果容器还是被拉伸,检查父元素是否有明确的尺寸限制,避免容器默认占满整个页面空间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 06:24:54