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

Chart.js 移除首尾X轴网格线并设置标签居中的实现问题

Chart.js 移除首尾X轴网格线并设置标签居中的实现问题

嘿,我来帮你搞定这个Chart.js的小问题!你现在靠加空标签和空数据来调整的方式有点绕,其实用Chart.js自带的配置项就能更优雅地实现你要的效果——移除首尾的X轴垂直网格线,同时让年份标签稳稳地居中显示。

我给你调整了代码,关键修改点和完整代码如下:

核心修改说明

  1. 简化数据结构:删掉原来标签数组里的空字符串,数据数组也不用留空了,直接用真实的年份和对应数据,结构更清晰。
  2. X轴精准配置:
    • 让标签居中:给ticks加align: 'center'
    • 移除首尾网格线:用grid.filter方法过滤掉第一条和最后一条垂直网格线
    • 去掉多余的边框和刻度线:关闭drawBorder和drawTicks,让图表更干净

完整修改后的代码

JavaScript 部分

new Chart(stats, {
  type: 'line',
  data: {
    labels: ['2021', '2022', '2023', '2024'],
    datasets: [{
      data: [100, 300, 200, 450],
      borderWidth: 4,
      borderColor: '#7168BD',
      backgroundColor: 'rgba(241, 163, 60, 0.1)',
      pointRadius: 5,
      pointHoverRadius: 8,
      pointBackgroundColor: "#7168BD",
      fill: true // 确保背景填充生效
    },
    {
      data: [250, 200, 250, 400],
      borderWidth: 4,
      borderColor: '#B6A76E',
      backgroundColor: 'rgba(230, 57, 70, 0.1)',
      pointRadius: 5,
      pointHoverRadius: 8,
      pointBackgroundColor: "#B6A76E",
      fill: true // 确保背景填充生效
    }]
  },
  options: {
    scales: {
      y: {
        grid: {
          color: '#B0B0B0',
          borderColor: 'transparent'
        }
      },
      x: {
        offset: true, // 让数据点不贴图表边缘,配合居中效果
        ticks: {
          align: 'center' // 标签居中显示
        },
        grid: {
          color: '#B0B0B0',
          borderColor: 'transparent',
          drawBorder: false, // 去掉X轴的边框
          drawTicks: false, // 去掉X轴的刻度小短线
          // 过滤掉首尾的垂直网格线
          filter: function(line) {
            const tickCount = this.chart.scales.x.ticks.length;
            return line.index !== 0 && line.index !== tickCount - 1;
          }
        }
      }
    },
    plugins: {
      legend: {
        display: false
      }
    },
    responsive: true
  }
});

HTML 部分

<canvas id="stats"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>

这样修改后,你就能得到和需求完全匹配的图表:首尾的垂直网格线消失了,年份标签整齐地居中显示在图表的对应位置,数据和样式也完全保留了你原来的设定~

备注:内容来源于stack exchange,提问作者Kareem Sultan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 19:02:57