ng2-charts - How to label y axis?

reCursed picture reCursed · Jul 11, 2019 · Viewed 7.2k times · Source

Unable to figure out how to label y axis using ng2-charts. Documentation only seems to have info on labelling x axis and using charts.js method directly yields no result.

Form component.ts:

  public barChartOptions = {
    scaleShowVerticalLines: false,
    maintainAspectRatio: false,

    yAxes: [{
      scaleLabel: {
        display: true,
        labelString: 'Frequency Rate'
      }}]
    //responsive: true
  };

HTML:

<script src="node_modules/chart.js/src/chart.js"></script>

<!--<button mat-button mat-raised-button color="primary" (click)="populate_data()">Update</button>-->

<div>
  <canvas baseChart class="chart" height ='450'

        [datasets]="barChartData"
        [labels]="barChartLabels"
        [options]="barChartOptions"
        [legend]="barChartLegend"
        [chartType]="barChartType">

      </canvas>
    </div>

Answer

terahertz picture terahertz · Jul 11, 2019

ng2-charts is a wrapper angular library around the original chart.js library.

The documentation in chart.js is more detailed: https://www.chartjs.org/docs/latest/charts/bar.html

how to label y axis using ng2-charts

In chart.js, y-axis's ticks are determined automatically based on the data you have pushed into ChartDataSets[]

E.g. max y-axis value will be 99

public barChartData: ChartDataSets[] = [
    { data: [5, 1, 99], label: 'Series A' },
    { data: [6, 10, 45], label: 'Series B' }
];

To control the appearance of y-axis's ticks, refer this documentation: https://www.chartjs.org/docs/latest/axes/cartesian/linear.html

So if you wish to control the tick's stepSize to be increment of 2 you can do something like:

yAxes: [{
   ticks: {
      stepSize: 2,
      beginAtZero: true
   }
}]

If you want to set the maximum y-axis tick label to be always 100, you will define your options like this:

yAxes: [{
   ticks: {
      max: 100
   }
}]

To label your y-axis:

public barChartOptions: ChartOptions = { // import { ChartOptions } from 'chart.js'; 
   ...
   responsive: true,
   maintainAspectRatio: false,
   ...
   scales: { //you're missing this
      yAxes: [{
         scaleLabel: {
            display: true,
            labelString: 'Frequency Rate'
         }
      }]
   }//END scales
};