1

I'm new to using ng2-charts in my application and I was wondering if I could increase the max value of the Y-axis by like 5 so that the top of my bar chart doesnt reach all the way to the top of the chart. Currently when I have a max value of 90, the max value of my Y-axis is also 90 and this causes some visually unpleasant overlap.

Bar chart

I'm currently using the default code from the documentation, which is as follows:

public barChartOptions: ChartOptions = {
    responsive: true,
    scales: { xAxes: [{}], yAxes: [{}] }
  };

  public barChartLabels: Label[] = [
    '2006',
    '2007',
    '2008',
    '2009',
    '2010',
    '2011',
    '2012'
  ];
  public barChartType: ChartType = 'bar';
  public barChartLegend = true;

  public barChartData: ChartDataSets[] = this.fetchData();

  public changeChart(): void {
    this.barChartType = this.barChartType === 'bar' ? 'line' : 'bar';
  }
iCV
  • 547
  • 1
  • 8
  • 29
  • https://stackoverflow.com/questions/44887677/chart-js-setting-max-y-axis-value-and-keeping-steps-correct Try this. – AliF50 Mar 27 '20 at 00:44

1 Answers1

1

Inside the ngOnInit method, you compute the maximum value found in any of your datasets.

const allValues = this.barChartData.flatMap(ds => ds.data);
const maxValue = Math.max(...allValues);

Then you define chart options and include yAxes.tick.max, giving it a value that is slightly bigger than maxValue.

yAxes: [{
  ticks: {
    max: Math.ceil(maxValue * 1.05)
  }
}]

The entire ngOnInit method would look as follows:

ngOnInit() {
  const allValues = this.barChartData.flatMap(ds => ds.data);
  const maxValue = Math.max(...allValues);
  this.barChartOptions = {
    responsive: true,
    scales: {
      yAxes: [{
        ticks: {
          max: Math.ceil(maxValue * 1.05)
        }
      }]
      }
  };
}

Please have a look at this StackBlitz

uminder
  • 23,831
  • 5
  • 37
  • 72