Displaying numerical values in data labels for a donut chart using Highcharts

Currently, I have a donut highchart displaying names in the data labels. However, I need to show numbers instead. Can someone guide me on how to achieve this?

This is my angular typescript code for the donut highchart:

import { Component, OnInit, Input, AfterViewInit } from '@angular/core';
import * as highcharts from 'highcharts';

@Component({
  selector: 'shared-highcharts-donought',
  templateUrl: './highcharts-donought.component.html',
  styleUrls: ['./highcharts-donought.component.scss']
})
export class HighchartsDonoughtComponent implements OnInit, AfterViewInit {

  plotData: Array<object>;
  colorCodes = ['#f2bf5e', '#4bb0b8', '#536eb7'];
  @Input() chartID: string;
  @Input() set chartData(value: object) {
    this.modifyInput(value);
  }
  constructor() { }

  modifyInput(value) {
    if (Array.isArray(value)) {
      this.plotData = value.map((v: {label: string, value: string}, i) => {
        return {
          name: v.label,
          y: +v.value,
          color: this.colorCodes[i],
        };
      }, this);
      console.log('plot data looks like ', this.plotData);
    }
  }

  ngAfterViewInit() {
    this.renderChart(this.chartID);
  }

  renderChart(chartID) {
    highcharts.chart(chartID, {
      title: null,
      responsive: {
        rules: [{
            condition: {
                maxWidth: 500,
            },
            chartOptions: {
                legend: {
                    align: 'center',
                    verticalAlign: 'bottom',
                    layout: 'horizontal'

                }
            }
        }]
    },
      chart: {
        height: (9 / 13 * 100) + '%',
        type: 'pie',
        plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false
      },
      credits: {
        enabled: false
      },
      plotOptions: {
        pie: {
          shadow: false,
        }
      },
      tooltip: {
        valueSuffix: 'hello',
        formatter: (val) => {
            return '<b>' + val['chart']['hoverPoint'].name + '</b><br/>: ' + val['chart']['hoverPoint'].percentage + ' %';
        }
    },
    series: [{
      type: 'pie',
      name: 'Feedback',
      data: [...this.plotData
      ],
      size: '100%',
      innerSize: '40%',
      showInLegend: false,
      dataLabels: {
          enabled: true,
          crop: false,
      }
    }],
    });
  }

  ngOnInit() {
  }

}

I am trying to display numbers (not percentages) in the data labels.

I have been stuck on this issue for a while now. Do I need to implement something similar to what I did for the tooltip? I attempted it but can't figure out where to get the values for the numbers.

Answer №1

If you want to customize the format of data labels in your Highcharts series pie chart, you can utilize the dataLabels.format property. This allows you to not only set the format but also include additional data like units if needed. For a variety of formatting options, you can check out the details here.

Give this snippet a try:

dataLabels: {
  enabled: true,
  crop: false,
  format: '{y}'
}

If you require more precise control over how the data labels are formatted, you can make use of the dataLabels.formatter option.

Answer №2

Considering incorporating the value into the label before interpreting data?

The concept is to conclude with:

const name = `${data.label}: ${data.value}`;

If integrated into your script:

this.plotData = value.map((v: {label: string, value: string}, i) => {
  return {
    name: `${v.label}: ${v.value}`,
    y: +v.value,
    color: this.colorCodes[i],
  };
}, this);

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

Experience the power of combining React with typescript, webpack, and ui-router-react for

After carefully studying the ui-router-react documentation (), I am encountering several challenges with webpack compilation when importing import {UIRouter, UIView, UISref, UISrefActive, pushStateLocationPlugin} from 'ui-router-react'; This is ...

The Ultimate Guide to Converting Enums to Object Types using Typescript

Imagine having an enum declared as follows: enum CustomerType { New = 'new', Owner = 'self', Loyal = 'subscriber' } Utilizing this enum can simplify checks like: if(customer.type === CustomerType.New) What is the re ...

Inject an asynchronous callback into the constructor of a class by leveraging TypeScript and Node with Passport integration

Currently, I am utilizing the passport-http authentication library. The issue at hand is that its documentation makes use of callbacks while my implementation involves TypeScript classes with async/await functionalities, thus causing uncertainty regarding ...

Angular: Nodemailer is encountering an abundance of runtime errors

Within my Angular project, I am attempting to utilize Nodemailer for sending emails. The initial issue arises when I try to import (after running npm i --save) as numerous errors occur when executing ionic serve. It's important to note that right aft ...

Why does `react/require-default-props` still display an error even when a default prop value has been set?

This inquiry pertains to the guideline require-default-props. Here is the code snippet in question: function MyComponent({ blubb = 'my default', }: { blubb?: string, }) { // blubb defaults to 'my default' }; Eslint is flagging a ...

What is the best way to customize the appearance of an Angular tree component?

I'm attempting to incorporate the style of the ACE Admin theme into the angular-tree-component. Currently, my tree looks like this: https://i.sstatic.net/ktiEf.png However, I desire to apply styles from the Angular tree guide in order to achieve a ...

Angular Universal experiences issues with route functionality after page reloads

Recently deployed an Angular Universal web app on Firebase. While all routes within the application are functioning properly, encountering errors when trying to access them externally. Below is the error message: functions: Starting execution of "ssr" ⚠ ...

Enhance your Typescript code with a type guard that supports optional wrapped types

I haven't come across a question similar to this one before. My goal is to develop a type guard that can accurately determine the type of a specific variable. It's quite simple with a single type. type A = { id: number, title: string, type: stri ...

Issue with accessing the 'subscribe' property in nested calls within Angular 2 due to it being undefined

I am trying to implement a subscription in company-list.component using the method getCompanies() from the company.service. However, I am encountering the following error: Cannot read property 'subscribe' of undefined Here is the code snippet ...

How can we ensure that Protractor's ElementArrayFinder 'each' function pauses until the current action has finished before moving on to the next iteration?

Currently, I am facing an issue while trying to utilize an 'each' loop in my Angular 8 app's end-to-end tests using protractor. Within my page object, I have created a method that returns an ElementArrayFinder. public getCards(): ElementArr ...

Learning the process of interpreting form data in Node.js

I'm currently working with Ionic Angular on the frontend and I am trying to send a formdata that includes a file along with two strings. It seems like the data is being sent successfully, but I am unsure how to access and read this information on the ...

Configuring .NET Core to send authentication cookies to a separate domain

I am facing an issue with using cookies on the frontend, which has a domain different from the backend. The backend is built with .Net Core and the frontend with Angular. I have learned that I need to set withCredentials: true when making http calls. Howev ...

Inquiring about Vue 3 with TypeScript and Enhancing Types for Compatibility with Plugins

I've been struggling to find a working example of how to implement type augmentation with Vue3 and TypeScript. I have searched for hours without success, trying to adapt the Vue2 documentation for Vue3. It appears that the Vue object in the vue-class ...

Creating a sticky header for a MatTable in Angular with horizontal scrolling

Having an issue with merging Sticky Column and horizontal scrolling. Check out this example (it's in Angular 8 but I'm using Angular 10). Link to Example The base example has sticky headers, so when you scroll the entire page, the headers stay ...

Downloading a JSON object in Angular 2: A step-by-step guide

How can I download a JSON object when clicking an icon in Angular 2? Below is the HTML: <i class="material-icons" (click)="download(model.model_id)">file_download</i> And here is the TypeScript code: download(mid){ let test = {"a":"b"} ...

Add a module to the main module or main component within the project

I have integrated a third-party library to manage the layout of my Angular application. I am considering importing it either in app.module.ts (the root module) or in app.component.ts (the root component). Do you think there would be any significant diff ...

Fetching information from a JSON source and storing it within an array of

I am currently facing an issue where I am unable to assign Exercise[] to Exercise. My goal is to retrieve data from a file, create a class object with the JSON values, and then add it to the class array to display as hardcoded JSON data. As someone who i ...

Provider not found: ConnectionBackend – NullInjectorError

I encountered the following error while attempting to load the webpage. Despite trying various suggestions from other sources, I have been unable to find a solution. Below the error stack lies my code. core.js:7187 ERROR Error: Uncaught (in promise): Null ...

What is the best way to develop an Angular library with components in version 8 that can be seamlessly integrated into upcoming Angular versions such as 12, 13, and 14

Do I need to implement a new technique or setup in order to understand this? Can we use Angular elements as the only solution, or are there alternative approaches available? ...

The Observable constructor in Nativescript must be called with the 'new' keyword in order to be invoked

I am facing a challenge while attempting to upload a multipart form in nativescript using http-background. The error message "Class constructor Observable cannot be invoked without 'new'" keeps appearing. I have tried changing the compilerOptions ...