[Chartjs]-How to set ticks on axes dynamically with chart.js?

4πŸ‘

It seems quite a long, but you can use below code to change the steps and max value based on input data.

ticks: {
            min: 0,
            callback: function(value, index, values) {
                if (Math.floor(value) === value) {
                    return value;
                }
            }
      }

0πŸ‘

  public seriesB: Array<number> = [
    59.023,
    59.023,
    59.034,
    59.034,
    59.034,
    59.039,
    59.05,
    59.061,
    59.088,
    59.104,
    500
  ];    

  public lineChartLabels: Array<any> = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July"
  ];

  public lineChartOptions: any = {
    title: {
      display: true,
      text: "Line Chart Example"
    },
    legend: {
      position: "bottom"
    },
    scales: {
      yAxes: [`k`
        {
          id: "SeriesB",
          ticks: {
          stepSize: 84,
          min:0
          }
        },
      ]
    }
  };
  
  public lineChartColors: Array<any> = [
    {
      backgroundColor: "rgba(255,255,255,0.2)",
      borderColor: "rgba(1,1,1)"
    }
  ];

  public lineChartData: Array<any> = [
    { data: this.seriesB, label: "SeriesB", yAxisID: "SeriesB" }
  ];

  public lineChartLegend: boolean = true;

  public lineChartType: string = "line";

  this.lineChartOptions.scales.yAxes[0].ticks.suggestedMin = Math.floor(
      Math.min(...this.seriesB)
    );
    this.lineChartOptions.scales.yAxes[0].ticks.suggestedMax = Math.ceil(
      Math.max(...this.seriesB)
    );
    );

Leave a comment