Creating Pie Charts with Chart.js using an array of objects as the dataset

I'm working with Chart.js and have my chart data formatted like this:

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

I want to create a classic pie chart from this data. Here is an example of what I am aiming for:

https://i.sstatic.net/T5Pi6.png

I've attempted to follow the guidance in the documentation, but it seems unavailable.

This is the template I am using:

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

Here is the TypeScript code associated with it:

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];
        }
      },
    },
  }
};

Answer №1

According to the documentation on Pie Chart Data Structure, it is specified that:

datasets must consist of an array of data points where each data point is a number,

It is important to adhere to the following structure:

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

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

To align your chartData with this structure, you can make the following transformations:

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

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

In the HTML element containing the baseChart component, ensure to pass the pieChartLabels to the [labels] attribute.

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

Check out the Demo (CustomPieComponent) on StackBlitz

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to locate the _app.js file within my Next.js project

After using "npx create-next-app" to set up my NextJs project, I came across a situation where I needed to define TransactionContext in _app.js. However, I encountered the issue that this file is not included in my project. Any assistance would be greatly ...

Encountering connection issues between Node.Js and Elasticsearch on Kubernetes due to a self-signed certificate within the certificate chain

I've set up a NodeJs application running on a Kubernetes cluster using microk8s. I followed the steps outlined in the official guide to configure Elasticsearch on Kubernetes. Problem However, I'm encountering difficulties connecting to the Elast ...

Show personalized names for breadcrumb links in Angular5

I recently added the ng5-breadcrumb package to my project to show breadcrumbs on the website. Here are the code modifications I made: In app.module.ts import { Ng5BreadcrumbModule, BreadcrumbService } from 'ng5-breadcrumb'; imports: [ ... ...

Angular 2: Enhancing User Experience with Pop-up Dialogs

Looking to implement a popup dialog that requests user input and returns the value. The popup component is included in the root component, positioned above the app's router outlet. Within the popup component, there is an open() method that toggles a ...

Angular is having trouble locating the module for my custom library

Trying to implement SSR in my angular application, but encountering an error when running npm run build:ssr. I've created my own library named @asfc/shared, which is bundled in the dist folder. ERROR in projects/asfc-web/src/environments/environment. ...

Executing angular 1 and angular 4 simultaneously within one browser tab

Is there a way to open my AngularJS 1 app running on port 3020 and an angular 4 app on port 4200 in the same tab by clicking a link? ...

Experiencing browser crashes following the incorporation of asynchronous functions into a JavaScript file. Seeking solutions to resolve this

In my recent project, I developed a basic online store application using vanilla javascript and ES6 classes. The shop items are stored in a JSON file which I used to populate the user interface. To implement functions like "addToCart", "quantityChange", a ...

Error: Headers already sent to the client, cannot set new headers

I am currently working on creating a basic API using passport-jwt and passport-local-mongoose. I have successfully set up all the JWT functions and created routes for registering and signing in users. One of these routes is meant to handle a GET request in ...

Angular: The type AbstractControl<any> cannot be assigned to type FormControl

I am working with a child component that includes an input tag <input [formControl]="control"> component.ts file @Input() control: FormControl; In the parent component, I am using it as follows: <app-input [control]="f['email ...

There are no shared properties with the type 'Properties<string | number, string & {}>'

Here's a look at my component: const linksContainerRef = useRef<HTMLDivElement>(null); const linksRef = useRef<HTMLUListElement>(null); const toggleLinks = () => { setShowLinks(!showLinks); }; interface LinkStyles ...

Tips for type guarding in TypeScript when using instanceof, which only works with classes

Looking for a way to type guard with TypeScript types without using instanceof: type Letter = 'A' | 'B'; const isLetter = (c: any): c is Letter => c instanceof Letter; // Error: 'Letter' only refers to a type, but is being ...

Ways to apply the pattern validator for 'Including solely numbers above 0'?

When using this form, I've noticed that adding a new ingredient works for any number, whether it's positive or negative. For example, if I add 'Bread with amount 5' it will display like this: https://i.sstatic.net/r6CHX.png Conversel ...

Creating an interactive questionnaire

Looking for insights on the following situation: I'm working with a survey structure that consists of questions and answers: questions: Question[]; answer: Answer[]; Where Question is defined as: export class Question { idQuestion: string; ...

When trying to construct a URL in a Next.js Appwrite project, a "TypeError" may occur, but it works perfectly fine when the URL is provided directly

I am currently following a tutorial on YouTube by JS Mastery about their HealthCare application using Next.js and Appwrite. I have obtained my API keys from the Appwrite cloud and added them to the .env.local file. However, upon running my project, I encou ...

Ensure that Template.fromStack() includes resources with the specified logical identifiers

Currently, I am overhauling a CDK stack in TypeScript that has reached the resource limit. Given that it includes stateful resources, I need to ensure that the revamped stack points to the same resources and not new ones that could lead to unfavorable resu ...

Properly utilizing an Angular API to assign JSON array values to an array

I have a JSON array of values: array1 = [{"type":"cc"},{"type":"vv"},{"type":3},{"type":4},{"type":5}]; There is another array, array2, which needs to be populated based on certain conditions. The condition states that the value with the type 'vv&ap ...

A guide to implementing includes() and indexOf() in Vuetify

Struggling with a code snippet in vuetify, facing issues: <template> ..... {{ countf(options[1], options[2], options[3], options[4], options[5]) }} ...... </template> <script lang="ts"> export default Vue.extend({ data () ...

To successfully navigate to another component view using routerLink in Angular 5, what specific requirements must be met?

My issue lies in the router link within company-details.component.html: <a class="btn btn-white btn-xs" [routerLink]="['/companyDetails', nextCompanyID]"> The path specified in my app.module.ts file is as follows: { path: 'companyDe ...

What is the best way to place a p-growl element in the bottom right corner of the page?

I've been struggling to fix the positioning of my growl message at the bottom right corner by overriding the CSS classes of p-growl. Initially, I attempted to override the .ui-growl class like this: ::ng-deep .ui-growl { position: fixed; b ...

Micro Frontend: Implementing a Pubsub System for Scalable Front-End Architecture

Currently, I am developing a large-scale application using the innovative micro front end architecture. The application is split into 5 Micro Apps: (micro-app-A (developed in Vue), micro-app-B (built with Vue), micro-app-C (using Angular), micro-app-D (cre ...