Search code examples
angularng2-charts

Implementing different Y-Axes for ng2-chart gives error "not assignable to type '_DeepPartialObject<{ type: "time"; } & Omit<CartesianScaleOptions"


I'm using ng2-charts on Angular 15 to display a line chart with two sets of data, one of the left side and the other on the right of the Y-Axis. I've followed the following code:


  public chart1Data: ChartConfiguration<'line'>['data'] = {
    labels: this.labelData,
    datasets: [
      {
        data: this.loadData,
        label: 'Engine Load',
        fill: false,
        tension: 0.5,
        borderColor: 'rgba(255,0,0,1)',
        backgroundColor: 'rgba(255,0,0,0.5)',
        yAxisID: 'y-axis-l',
      },
      {
        data: this.rpmData,
        label: 'Engine speed (RPM)',
        fill: false,
        tension: 0.5,
        borderColor: 'rgba(255,128,0,1)',
        backgroundColor: 'rgba(255,128,0,0.3)',
        yAxisID: 'y-axis-r',
      },
    ],
  };

  public lineChartOptions: ChartOptions<'line'> = {
    responsive: true,
    scales: {
      yAxes: [
        {
          id: 'y-axis-l',
          position: 'left',
        },
        {
          id: 'y-axis-r',
          position: 'right',
        }
      ]
    }
  };

  public lineChartLegend = true;

But the app crashes saying


error TS2322: Type '{ id: string; position: string; }[]' is not assignable to type '_DeepPartialObject<{ type: "time"; } & Omit<CartesianScaleOptions, "max" | "min"> & { min: string | number; max: string | number; suggestedMin: string | number; ... 5 more ...; ticks: { ...; }; }> | ... 4 more ... | undefined'.
  Type '{ id: string; position: string; }[]' is not assignable to type '_DeepPartialObject<{ type: "timeseries"; } & Omit<CartesianScaleOptions, "max" | "min"> & { min: string | number; max: string | number; suggestedMin: string | number; ... 5 more ...; ticks: { ...; }; }>'.
    Types of property 'reverse' are incompatible.
      Type '() => { id: string; position: string; }[]' is not assignable to type 'boolean | undefined'.

152       yAxes: [
          ~~~~~

What could be the issue behind this and how do I rectify it?


Solution

  • I believe that your current configuration with multiple axes is for version 1.0, which is no longer supported after version 2.0.

    While Chart.js does support multiple axes by specifying the xAxisID and/or yAxisID according to the documentation.

    Under the scale object, specify the key-value pair with the key as the axisID and the value as the configuration for particular axisID.

    public lineChartOptions: ChartOptions<'line'> = {
      responsive: true,
      scales: {
        'y-axis-l': {
          position: 'left',
        },
        'y-axis-r': {
          position: 'right',
        },
      },
    };
    

    Reference: Multi Axis Line Chart