How do I customize y-axis labels and randomly pick the value from the data range for x-axis in Chart js

I have been working on a chart using charts.js that show workouts duration each day. The y-axis should have dates and the x-axis should have the duration of the Series, Here is my dataset:

    public lineChartData: ChartDataSets[] = [
    { data: [65, 19, 40, 81, 56, 5, 40], label: 'Series A' },
    { data: [95, 69, 40, 81, 56, 96, 40], label: 'Series B' },
    { data: [65, 74, 40, 41, 54, 55, 40], label: 'Series C' }
  ];
  public lineChartLabels: Label[] = ['2020/05/20', '2020/05/21', '2020/05/22', '2020/05/23', '2020/05/24', '2020/05/25'];

So far I am unable to find any implementation-related it, it would be very helpful if anyone can help me out on this. I have tried the stackblitz with horizontal with a bar chart, we need to same like in LINE CHART Here is stackblitz link

1 answer

  • answered 2020-09-14 09:22 uminder

    You need to use a scatter chart and define the option showLine: true on each dataset. Further you have to define the y-axis as a time cartesian axis as follows.

    yAxes: [
      {
        type: "time",
        time: {
          parser: "YYYY/MM/DD",
          unit: "day",
          displayFormats: {
            day: "YYYY/MM/DD"
          }
        },
        ticks: {
          reverse: true
        }       
      }
    ]
    

    Since the scatter chart expects the data in point format, you have to generate appropriate data structure in the ngOnInit method as follows:

    ngOnInit() {
      this.lineChartData.forEach(ds => {
        ds.data = ds.data.map((v, i) => ({ x: v, y:  this.lineChartLabels[i] }));
      });
    }
    

    Also remove [labels]="lineChartLabels" from the canvas, this is not needed when defining the data in point format.

    Unfortunately however ng2-charts can't cope with this configuration and displays wrong colors for the data points and the legend labels. Therefore I also had to remove [colors]="lineChartColors" from the canvas and define the colors on the datasets. You'll probably have to get rid of this wrapper library and use Chart.js directly in order to obtain the expected result.

    Please take a look at your amended code in this StackBlitz.