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

React-Chart-JS柱状图问题:消除间距、居中对齐并设50厚度

解决React-Chart.js柱状图间距、对齐及厚度问题

要实现消除柱子间距、柱子居中对齐、固定柱子厚度50px的效果,需同时调整数据集与坐标轴配置,具体方案如下:

核心配置要点

  1. 消除间距+固定厚度:在数据集里设置barThickness: 50锁定柱子厚度,同时将barPercentage和categoryPercentage都设为1,让柱子完全填充分类宽度,彻底消除间距。
  2. 居中对齐:在x轴配置中开启offset: false,关闭默认偏移,使柱子与分类标签居中对齐;可额外隐藏x轴网格线,优化视觉效果。

修改后的代码示例

import React from "react";
import { Bar } from "react-chartjs-2";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend
} from "chart.js";

ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend
);

export default function App() {
  const options = {
    responsive: true,
    plugins: {
      legend: { position: "top" },
      title: { display: true, text: "React Chart.js Bar Chart" }
    },
    scales: {
      x: {
        offset: false, // 关闭偏移实现居中
        grid: { display: false } // 隐藏x轴网格线
      }
    }
  };

  const labels = ["January", "February", "March", "April", "May", "June", "July"];

  const data = {
    labels,
    datasets: [
      {
        label: "Dataset 1",
        data: labels.map(() => Math.floor(Math.random() * 100)),
        backgroundColor: "rgba(255, 99, 132, 0.5)",
        barThickness: 50, // 固定柱子厚度
        barPercentage: 1, // 柱子占满分类宽度
        categoryPercentage: 1 // 分类宽度占满可用空间
      }
    ]
  };

  return <Bar options={options} data={data} />;
}

效果对比

  • 当前效果:current output
  • 预期效果:desired output

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 22:45:38