schutte
schutte

Reputation: 2166

How to hide labels by two ticks? chartjs

How can we customize labels and hide it 2 ticks/line (see the expected output below)? I already tried the code below but it did nothing. Is there any chance we can hide it specifically?

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

Here is my working code like click link here


Current Output

enter image description here

Expected Output

enter image description here

Upvotes: 0

Views: 835

Answers (2)

Catalin
Catalin

Reputation: 11731

You need to use options.scales.yAxes[0].ticks.callback function

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;
            }
          }
        }]
      }
    };
}

Upvotes: 1

DarkTrick
DarkTrick

Reputation: 3529

Note: @Catalin 's answer is problematic. Problem: He/She is returning "" in case the label should be hidden. However, you should return null.

Generalized answer

You need to use the options.scales.yAxes.ticks.callback function

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

Why is null so important?

The impact becomes clear on the xAxes: Returning null tells chartjs that there is no label.
example when null is returned

Returning "" tells chartjs that there is a label. That means, it reserves space. In this case the labels are slanted:
example when an empty string is returned

Upvotes: 1

Related Questions