Home > Software engineering >  Chart.js - How to parse array of objects as the dataset for Pie Chart
Chart.js - How to parse array of objects as the dataset for Pie Chart

Time:01-19

I have Chart.js and chart data in this format:

chartData = [
  { data: 2, label: 'Label 1' },  
  { data: 10, label: 'Label 2' },  
  { data: 40, label: 'Label 3' },
];

How can I parse my data to get a classic pie chart like this:

enter image description here

I have tried to follow the documentation but it is not available.

This is my template:

<canvas baseChart
        [datasets]="chartData"
        [type]="pieChartType"
        [options]="pieChartOptions">
</canvas>

and here is my ts:

chartData = [
  { data: 2, label: 'Label 1' },  
  { data: 10, label: 'Label 2' },  
  { data: 40, label: 'Label 3' },
];

public pieChartOptions: ChartConfiguration['options'] = {
  responsive: true,
  plugins: {
    legend: {
      display: true,
      position: 'top',
    },
    datalabels: {
      formatter: (value, ctx) => {
        if (ctx.chart.data.labels) {
          return ctx.chart.data.labels[ctx.dataIndex];
        }
      },
    },
  }
};

CodePudding user response:

From the Pie Chart Data Structure docs, it mentions that:

datasets need to contain an array of data points. The data points should be a number,

You need to follow its structure as below:

public pieChartDatasets = [
  {
    data: [300, 500, 100],
  },
];

labels = [
    'Red',
    'Yellow',
    'Blue'
];

Well, you can transform your chartData to match its structure:

pieChartLabels: string[] = [];
pieChartDatasets: any[] = [];

this.pieChartLabels = this.chartData.map((x) => x.label);
this.pieChartDatasets = [
  {
    data: this.chartData.map((x) => x.data),
  },
];

And in the baseChart HTML element, pass the pieChartLabels to [labels] attribute.

<canvas
  baseChart
  [datasets]="pieChartDatasets"
  [type]="pieChartType"
  [options]="pieChartOptions"
  [labels]="pieChartLabels"
>
</canvas>

Demo (CustomPieComponent) @ StackBlitz

  • Related