如何通过两个刻度隐藏标签?chartjs

bqujaahr  于 2022-11-07  发布在  Chart.js
关注(0)|答案(2)|浏览(211)

我们如何自定义标签并将其隐藏2个刻度/线(见下面的预期输出)?我已经尝试了下面的代码,但它什么也没做。有没有可能我们可以专门隐藏它?

legend: {
   labels: {
      filter: function(label) {
         if (label.text === '10' || label.text === 10) return false;
      }
   }
},

下面是我的工作代码,如click link here

电流输出

预期输出

cvxl0en2

cvxl0en21#

您需要使用options.scales.yAxes[0].ticks.callback函数

render() {
    const options = {
      responsive: true,
      legend: {
        display: false
      },
      type: "bar",
      scales: {
        yAxes: [{
          ticks: {
            callback: function(value, index, values) {
              if (index % 2 === 0) {
                return value;
              }
              return null;
            }
          }
        }]
      }
    };
}
of1yzvn4

of1yzvn42#

注:@Catalin的回答有问题问题:他/她将返回"",以防标签被隐藏。但是,您应该返回null

概括性答案

您需要使用options.scales.yAxes.ticks.callback函数

const options = {
  scales:{
    yAxes: {
      ticks: {
        callback: function(value, index, values) {
          if (index % 2 === 0) {
            return value;
          }
          return null; // <- NOT ""
        }
      }
    } 
  }
}

为什么null如此重要?

xAxes上的影响变得很明显:返回null告诉chartjs * 没有标签 *。

返回""告诉chartjs * 有一个标签 *。这意味着它保留了空间。在本例中,标签是倾斜的:

相关问题