1

I wanted to know is there a way that I can control how many labels get to be displayed - I know there is the stepSize feature but that is numerical. I am looking for something like interval:3 so it will show every third label on the graph.

options: {
  scales: {
      xAxes: [{
        ticks: {
          beginAtZero:true,
          max: 100
        }
      }],
        yAxes: [{
          ticks: {
          }
        }]
    }
}

This is how i am rendering my chart:

html:

<div class="chart-container" style="position: relative; height:20vh; width:40vw">
      <canvas id="chartGraph"   baseChart [colors]="colorsOverride" [datasets]="barChartData" [labels]="barChartLabels" [options]="barChartOptions" [legend]="false" [chartType]="barChartType">
      </canvas>
</div>

in my component.ts i have:

barChartOptions: any = {
    scaleShowVerticalLines: false,
    responsive: true,
    scales: {
      xAxes: [{
        ticks: {
          beginAtZero:true,
          max: 100
        }
      }],
        yAxes: [{
          ticks: {

          }
        }]
    },
      tooltips:{
        mode: 'point'
      }
  };
  barChartLabels: string[] = [];
  barChartType: string = 'horizontalBar';
  barChartLegend: boolean = false;
  barChartData: any[] = [];
  data: any;

  colorsOverride: Array<Color> = [{
    backgroundColor: '#6aaf6a',
    hoverBackgroundColor: 'purple'
  }];

    getChartData(link:string){
        this.service.getQuery(link).subscribe(
            data => {
                this.data = data;
                this.barChartLabels = this.data.map(x => x.display);
                this.chartData = this.data.map(x => x.value);
                this.barChartData = [{data: this.chartData, label:'sample' }];
            }
        );
    }
bluePearl
  • 1,237
  • 4
  • 24
  • 42
  • @ℊααnd this is more of a numeric interval but i am looking for label interval so like it shows the labels of January, March, May.... yet the bar graphs will show for each month. (based on your example) – bluePearl Jul 11 '17 at 08:30
  • @ℊααnd yes - what property did you use? – bluePearl Jul 11 '17 at 08:51

1 Answers1

0

Source: Limit labels number on Chart.js line chart

The example provided by George blanks every other label.

 var options =  {  
     scales: {
        xAxes: [{
            afterTickToLabelConversion: function(data){

                var xLabels = data.ticks;

                xLabels.forEach(function (labels, i) {
                    if (i % 2 == 1){
                        xLabels[i] = '';
                    }
                });
            } 
        }]   
    }
}

To retain the first value in the X axes, and then the fourth, eighth, and so on, you could change the if statement to:

if (i % 4 != 0){ 
    xLabels[i] = ''; 
}

The solution works well for yAxes options as well. The variable name xLabels is not a part of chartjs and no harm will come from altering it.

James Valeii
  • 472
  • 1
  • 4
  • 14