Positioning Data Labels Outside of Pie or Doughnut Charts in Chart.js

I am currently working on a large-scale project and I am in need of a way to position the labels outside of pie charts or doughnut charts. I came across a plugin called outerLabels on GitHub which seems to be the perfect solution for what I need, but I am having difficulty getting it to function properly.

I have tried various methods to implement the plugin using Chart.js, including importing it as shown below:

import {} from 'chartjs-plugin-outerlabels';
import 'chartjs-plugin-outerlabels';

Here is an example of how I am configuring the chart options:

function getPieChartOptions(chartTitle: string) {
    const options: ChartOptions = {
        responsive: true,
        plugins: {
            outerLabels: {
                fontNormalSize: 12,
                fontNormalFamily: 'sans-serif',
            },
            legend: {
                display: true,
                labels: {
                    usePointStyle: true,
                    font: {
                        family: 'sans-serif',
                        size: 12,
                    }
                }
            },
            title: {
                display: true,
                text: chartTitle,
                color: 'black',
                padding: 5,
                font: {
                    size: 16,
                    family: 'sans-serif',
                }
            },
            datalabels: {
                color: 'white',
                formatter: commas.format,
            }
        },
    };
    return options;
}

Below is an example of a doughnut chart that is part of the project itself:

If anyone has experience with this plugin or any other suggestions on how to achieve my goal, I would greatly appreciate your help!

Answer №1

I've successfully implemented this code snippet without the need for the datalabels field (since it requires installation of the chartjs-plugin-datalabels.js library).

Basically, the configuration in the ChartOptions is quite similar to the one you have provided.

import 'chartjs-plugin-outerlabels';

getPieChartSettings(chartTitle: string) {
  const options: ChartOptions<'doughnut'> = {
    responsive: true,
    plugins: {
      outerLabels: {
        fontNormalSize: 12,
        fontNormalFamily: 'sans-serif',
      },
      legend: {
        display: true,
        labels: {
          usePointStyle: true,
          font: {
            family: 'sans-serif',
            size: 12,
          },
        },
      },
      title: {
        display: true,
        text: chartTitle,
        color: 'black',
        padding: 5,
        font: {
          size: 16,
          family: 'sans-serif',
        },
      },
      tooltip: {
        enabled: false,
      },
    },
  };
  return options;
}

Below is the code to visually represent the chart on the canvas element.

@ViewChild('MyChart', { static: true }) chart: ElementRef<HTMLCanvasElement>;

ngAfterViewInit() {
  const ctx = this.chart.nativeElement.getContext('2d');
  new Chart<'doughnut'>(ctx, {
    type: 'doughnut',
    data: {
      labels: [['Download', 'Sales'], ['In', 'Store', 'Sales'], 'Mail Sales'],
      datasets: [
        {
          data: [300, 500, 100],
        },
      ],
    },
    options: this.getPieChartSettings('doughnut'),
  } as ChartConfiguration<'doughnut'>).draw;
}

Check out the Demo 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

Divided Progress Indicators in Bootstrap 3

Looking to enhance user experience on my webpage by creating a progress bar for data entry. The goal is for users to enter 10 items before proceeding. The challenge I'm facing is developing a progress bar that accurately reflects the number of items ...

Error with TypeScript Compiler in Angular 2

Currently, I am facing an issue while trying to run tsc in my Angular 2 application directory. The error message I receive is: Error TS5023: Unknown compiler option 'moduleResolution'. This issue seems to be hindering the startup process, as ts ...

Is it possible to shift the div inline-block using the CSS :after selector?

I'm looking to adjust the placement of the disk icon so that it aligns more with the baseline of the text without increasing the vertical space between lines. Below is the CSS code I've worked on so far: .openPage:after { content: ' &a ...

The left and right DIVs are not automatically adjusting to the height of the container

I am currently working on a grid layout consisting of 9 div tags, creating 3 rows with 3 divs in each row. Within this grid, each div is supposed to have a background image, except for the second div in the second row. My main challenge lies in getting th ...

Encountering a CORS problem when an Angular application communicates with a .NET Core API integrated with the Sustainsys.Saml2 library and Azure Active Directory serving as the Identity

Our team is currently working on implementing SAML authentication in a .NET Core API to handle requests coming from an Angular application. We are utilizing the package Sustainsys.Saml2.AspNetCore2 (version 2.9.2) for .NET 6, and we have successfully set u ...

Most effective method for sending an HTTP Post request with a JSON body in Angular 9

Hi there, I'm currently working on a project that requires saving information from 3 text box fields. I've been struggling to figure out how to make a POST request with a JSON body. Here's what I have so far: I've been piecing together ...

Leverage predefined JavaScript functions within an Angular template

I have been attempting to execute an eval function within my angular template in the following manner: <div *ngFor="..."> <div *ngIf="eval('...')"></div> </div> You understand what I'm trying to ...

Angular button debounce time upon click

I'm just getting started with RXJS and I'd like to add debounce time when clicking on a button. Here's the code for my button: <button mat-mini-fab (click)="send()" [disabled]="!message.text || message.text.length === 0 || ...

The specified 'contactId' property cannot be found within the data type of 'any[]'

I am attempting to filter an array of objects named 'notes'. However, when I attempt this, I encounter the following error: Property 'contactId' does not exist on type 'any[]'. notes: Array < any > [] = []; currentNot ...

Validating Forms in TypeScript

Currently in the process of learning Angular 10, but encountering a challenge I have an HTML document that validates a form group in my component. When I set a value for a textbox from my component, the value is displayed correctly, but my submit button c ...

Creating dynamic DOM elements in Angular templates by utilizing variable values as element types

There's a component I'm working with that I want to render either as a div or span dynamically. To achieve this, I've created an input variable called elementType. Now, the challenge is how to properly render it in the template. Here's ...

Error: The reference to "global" is undefined and was not caught in the promise

After successfully running my project, I encountered an issue upon installing the aws-sdk package from here. Despite trying to find solutions online, I have been unable to resolve this problem. The error message I am facing is: core.js:1673 ERROR Error ...

Creating a Full Height Background Image with a Responsive Width Using Jquery

I am facing an issue with my background image dimensions of 1400 in height and 1000 in width. When using any full-screen background jQuery plugin or code, the image crops from either the top or bottom to fit the entire screen. However, I am looking for a s ...

Encountered an issue while deploying Angular files to Azure StorageAccount: Failed to load resource

After successfully deploying Angular dist files to a Container named myui in Azure StorageAccount using Azure Copy, I have encountered an issue. The files are available in the Container, but when trying to access them through the Blob url https://uistorage ...

Using jQuery to toggle visibility on click within WordPress

Looking for a way to make three buttons change color on hover and display different content when clicked? You're not alone! Despite searching through tutorials and forums, the solution remains elusive. The buttons are structured like this: <div i ...

Restarting an Angular app is necessary once its HTML has been updated

I've encountered an interesting challenge with an application that combines MVC and Angular2 in a not-so-great way. Basically, on the Index page, there's a partial view loading the Angular app while also including all the necessary JavaScript li ...

The fuse-sidebar elements are not being properly highlighted by Introjs

I have recently developed an angular project that utilizes the fuse-sidebar component. Additionally, I am incorporating introjs into the project. While introjs is functioning properly, it does not highlight elements contained within the fuse-sidebar. The ...

Expanding the width of the containing div using CSS

I have a main container with multiple smaller divs inside it. None of these small divs have specified widths. I want the black div to expand and fill up the entire space, stretching all the way to the ABC div on the right. This only needs to work in Chr ...

Tap to navigate to queued sections on click

Greetings, community members! Despite my extensive research, I have been unable to find a solution to my query. Just a heads up - I am a novice when it comes to javascript and jQuery. My question pertains to incorporating two image buttons that, upon cli ...

Encountering issues with styling the search bar using CSS and unable to see any changes reflected

I am currently working on creating a searchBar and customizing its CSS, but unfortunately, most of the styling properties seem to not be taking effect. So far, only changing colors seems to work as expected. .mainBar{ background-color: blue; width: ...