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

如何在Chart.js 4.2.1垂直柱状图中设置Y轴正负整数值

问题描述

使用Chart.js 4.2.1制作垂直柱状图,当前Y轴包含正负数值,希望以零点为基准,上下均显示正整数,请问该如何实现?

目标效果示例图:
目标柱状图效果

当前实现代码:

var MONTHS = [
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December",
];
var color = Chart.helpers.color;
var barChartData = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [
    {
      label: "Dataset 1",
      backgroundColor: 'rgba(255, 201, 14, 1)',
      borderColor: 'rgba(255, 201, 14, 1)',
      borderWidth: 1,
      data: [10, 20, 30, 40, 50],
    },
    {
      label: "Dataset 2",
      backgroundColor: 'rgba(255, 201, 14, 1)',
      borderColor: 'rgba(255, 201, 14, 1)',
      borderWidth: 1,
      data: [-100, -200, -300, -400, -500],
    },
  ],
};

var ctx = bloodPressureChart;
new Chart(ctx, {
  type: "bar",
  data: barChartData,
  options: {
    responsive: true,
    legend: {
      position: "top",
    },
    title: {
      display: true,
      text: "Chart.js Bar Chart",
    },
  },
});

当前图表效果:
当前柱状图效果

解决方案

要实现Y轴零点上下均显示正整数,只需在图表配置的options中添加Y轴自定义刻度逻辑:

  1. 通过scales.y.ticks.callback将所有刻度值转换为绝对值,实现正负区域都显示正整数;
  2. 配置beginAtZero确保Y轴以零点为分界,alignToPixels保证刻度对齐精度。

修改后的完整代码如下:

var MONTHS = [
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December",
];
var color = Chart.helpers.color;
var barChartData = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [
    {
      label: "Dataset 1",
      backgroundColor: 'rgba(255, 201, 14, 1)',
      borderColor: 'rgba(255, 201, 14, 1)',
      borderWidth: 1,
      data: [10, 20, 30, 40, 50],
    },
    {
      label: "Dataset 2",
      backgroundColor: 'rgba(255, 201, 14, 1)',
      borderColor: 'rgba(255, 201, 14, 1)',
      borderWidth: 1,
      data: [-100, -200, -300, -400, -500],
    },
  ],
};

var ctx = bloodPressureChart;
new Chart(ctx, {
  type: "bar",
  data: barChartData,
  options: {
    responsive: true,
    legend: {
      position: "top",
    },
    title: {
      display: true,
      text: "Chart.js Bar Chart",
    },
    scales: {
      y: {
        beginAtZero: true,
        alignToPixels: true,
        ticks: {
          // 将刻度值转为绝对值显示
          callback: function(value) {
            return Math.abs(value);
          }
        }
      }
    }
  },
});

关键说明:

  • ticks.callback函数接收每个刻度的原始数值,返回Math.abs(value)即可把负数刻度转为正整数显示;
  • 若需要控制刻度间隔,可添加ticks.stepSize参数(如stepSize: 50)来调整刻度密度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 05:34:55