Home > Mobile >  NG2-Charts - How to change cutout width for doughnut chart
NG2-Charts - How to change cutout width for doughnut chart

Time:01-18

I am working on a corporate project using Angular 14, ChartJS (4.1.2), and NG2-Charts (4.1.1). and I am having some trouble when trying to change the width of the doughnut chart. I show a picture of what I have now:

Chart what I have

And this is what I am supposed to do:

Chart I want

At this moment I do not need to put text inside the chart, I just want to reduce the size of the chart, so the text inside fits well.

I have already tried this answer, and this one, but none of these work and I do not know why.

Here is my HTML code:

<canvas baseChart  
        style="height: 15vh; max-height: 15vh" 
        [data]="doughnutChartData"
        [type]="doughnutChartType" 
        [options]="doughnutChartOptions">
</canvas>

And the TS code:

public doughnutChartLabels: string[] = ['a', 'b', 'c'];
public doughnutChartData: ChartData<'doughnut'> = {
  labels: this.doughnutChartLabels,
  datasets: [
    {
      data: [600, 400, 200],
      backgroundColor: [
        '#AAAAAA',
        '#BBBBBB',
        '#CCCCCC',
      ],
    },
  ],
};
public doughnutChartType: ChartType = 'doughnut';
public doughnutChartOptions: ChartConfiguration['options'] = {
  responsive: true,
  plugins: {
    legend: {
      display: false,
    },
    datalabels: {
      anchor: 'end',
      align: 'end'
    },
  }
};

When I try to add this <'doughnut'> to my chart options, it breaks the type, and when I remove the type from the HTML, it becomes a bar chart, so I am stuck here.

CodePudding user response:

Besides changing the doughnutChartOptions type as ChartConfiguration<'doughnut'>['options'], you also need to change the doughnutChartType as ChartConfiguration<'doughnut'>['type'] type.

public doughnutChartType: ChartConfiguration<'doughnut'>['type'] = 'doughnut';
public doughnutChartOptions: ChartConfiguration<'doughnut'>['options'] = {
  responsive: true,
  plugins: {
    legend: {
      display: false,
    },
    datalabels: {
      anchor: 'end',
      align: 'end',
    },
  },
  cutout: '90%',
};

Demo @ StackBlitz

CodePudding user response:

Normally adding <'doughnut'> shouldn't break your code. I found a similar issue in here. Try changing either the ng2-charts or the chartJS version in your app.

Here's an example: public ChartOptions: ChartOptions<'doughnut'> = { options: { cutout: "99%" } };

  • Related