Tips for showing both label and value on a pie slice in Apex charts

I am currently utilizing apex chart within an angular application to showcase charts. I am specifically focusing on a pie chart and aiming to customize it by displaying labels on the values within each slice of the pie, similar to what is shown in the attached image. Unfortunately, I have not been able to find a solution for this yet. Any guidance or direction would be greatly appreciated. Thank you.

screenshot [1]: https://i.stack.imgur.com/vMcHk.png

import { ChartComponent, ApexLegend, ApexDataLabels, ApexFill, ApexPlotOptions, ApexNonAxisChartSeries, ApexResponsive, ApexChart } from 'ng-apexcharts';

export interface ChartOptions {
  series: ApexNonAxisChartSeries;
  chart: ApexChart;
  responsive: ApexResponsive[];
  labels: any[];
  legend: ApexLegend;
  dataLabels: ApexDataLabels;
  fill: ApexFill;
  plotOptions: ApexPlotOptions;
}

export class PieChartComponent implements OnInit {
  @ViewChild('chart') chart: ChartComponent;
  public chartOptions: Partial<ChartOptions>;

  constructor() {}

  ngOnInit(): void {
    this.chartOptions = {
      series: [70.48, 29.52],
      chart: {
        width: 380,
        type: 'pie',
        toolbar: {
          tools: {
            download: false,
          },
        },
      },
      legend: {
        show: false,
      },
      labels: ['DII', 'FII'],
      fill: {
        colors: ['#ffe163', '#694fb6'],
      },
      plotOptions: {
        pie: {
          startAngle: 110,
        },
      },
      dataLabels: {
        style: {
          fontSize: '14',
          fontWeight: '600',
          colors: ['#000000', '#ffffff'],
        },
      },
      responsive: [
        {
          breakpoint: 480,
          options: {
            chart: {
              width: 400,
            },
            legend: {
              position: 'bottom',
            },
          },
        },
      ],
    };
  }
}
<apx-chart
    [series]="chartOptions.series"
    [chart]="chartOptions.chart"
    [labels]="chartOptions.labels"
    [responsive]="chartOptions.responsive"
    [legend]="chartOptions.legend"
    [dataLabels]="chartOptions.dataLabels"
    [fill]="chartOptions.fill"
    [plotOptions]="chartOptions.plotOptions"
  ></apx-chart>

Answer №1

If you want to customize pie chart slice labels and values as seen in the attached screenshot, follow these instructions:

To achieve this, utilize the dataLabels option for customizing the label.

Include the following two options in your chart settings and apply them to the

<apex-chart></apex-chart>
component in your HTML file:

dataLabels: {
        enabled: true,
        formatter: function (val, opt) {
          // return [] used to change the line for the labels
          // each index element will get rendered to a new line
          /* Also casted to know (unknown) first and then to (string) as library is currently 
             accepting return type as string only. so it's a small manipulation 
             until library does not accept array. */
          switch (opt.seriesIndex) { // seriesIndex gives the position of slice
            case 0:
              return [ 'Housing', '$000.00 | ' + val as string + '%' ] as unknown as string;
            case 1:
              return [ 'Credit', '$000.00 | ' + val as string + '%' ] as unknown as string;
            case 2:
              return [ 'Transportation', '$000.00 | ' + val as string + '%' ] as unknown as string;
            case 3:
              return [ 'Living', '$000.00 | ' + val as string + '%' ] as unknown as string;
            case 4:
              return [ 'Miscellaneous', '$000.00 | ' + val as string + '%' ] as unknown as string;
            default:
              return val as string;
          }
        },
        style: {
          fontSize: "13",
          colors: ['#404040'],
          fontWeight: '100',
          fontFamily: 'Arial'
        },
},
plotOptions: {
        pie: {
          dataLabels: {
            offset: 20, // Moving the label position on slice
          }
        }
}

Implementing the above options will display the labels similar to those shown in the image below

https://i.stack.imgur.com/zvdJF.png

This guidance should be beneficial to you or others! Thank you.

Keep enjoying coding :-)

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

Tips for adjusting text to fit within a container without needing to use overflow:auto

Is there a way to prevent text overflow in a container without using the overflow:auto property? I've come across plugins that automatically reduce the text size, but I'm not keen on that solution. What I want is for long words or URLs to wrap on ...

Certain images are not being retrieved by Express on Linux, although they are functioning properly on Windows

When using a template to display HTML code, everything works smoothly on Windows. However, when transferring the code to a Linux machine, an issue arises - "Cannot GET /SmallVacImages/1.jpg". It seems that the index.html file can load images from the publi ...

How is it possible to inject various data services into individual components within an Angular2 application?

If you're working on a typical task management app called TaskMaster, There's a main TaskMaster component that offers a TaskManager service to handle all the task data. You've created a MainComponent that provides this TaskManager and inje ...

Native JavaScript does not handle AJAX responses correctly

I'm facing an issue with my ajax call where the returned HTML works well on changes, but the Javascript that should perform actions based on clicks within the results is not functioning properly. Here is the ajax call: function update_order_shipp ...

Update the style class of an <img> element using AJAX

My success with AJAX enables PHP execution upon image click. However, I seek a real-time visual representation without page reload. Thus, I aim to alter <img> tag classes on click. Presently, my image tag resembles something like <img title="< ...

Limit the implementation of Angular Material's MomentDateAdapter to strictly within the confines of individual

Within my app, I have several components that utilize the mat-datepicker. However, there is one component where I specifically want to use the MomentDateAdapter. The issue arises when I provide it in this one component as it ends up affecting all the other ...

Ways to Get Rid of Line Beneath the Table

Can anyone assist me in removing the underline at the bottom of my table? Here is the code I am using: <table> <tbody> <tr> <td><iframe src="//player.vimeo.com/video/99496559" width="220" height="150" frameborder="0" allowfull ...

Finding out if an array is empty or not in Reactjs: A Quick Guide

I am currently working with Reactjs and Nextjs. I am using axios to fetch data, and I need a way to determine if the array (students.data) is empty before running a map or loop. How can I achieve this? Here is the code snippet I am working with: const [stu ...

Troubles arising while submitting data from AngularJS to Amazon S3

I am currently in the process of developing an application using the MEAN (MongoDB, Express, AngularJS, node.js) stack where I need to upload image files to Amazon S3. Here is my approach: Initially, an http get request is sent to my API which outlines th ...

What is the best way to ensure that table cells containing images resize without any issues?

I need help with centering and resizing an image on a screen. The image is divided into small images within cells, but I can't seem to get it right. Despite trying various solutions and spending hours resizing the table and images, the final output a ...

The specified subpath './lib/tokenize' does not match any defined "exports"

As a newcomer to React, I've been facing some challenges while trying to get started. Despite searching on Google and other platforms, I couldn't find a solution to my problem. I was attempting to run code from a YouTube channel called Lama Dev b ...

What is the best method for loading JSONP data in Internet Explorer?

This code snippet functions flawlessly in FF, Chrome and Safari, however IE does not accept it. $(function() { var access_token = location.hash.split('=')[1]; $.ajax({ type: "GET", dataType: "jsonp", cache: false, url: "htt ...

The Node.js server delivers a different object to the client

I'm facing an issue while trying to send an object from the client to a Node.js server. Here is my Ajax call: $.ajax({ url: config.api.url, type: config.api.method, contentType: config.api.contentType, // application/x-www-form-urlencoded; cha ...

I encountered an error message while running the Angular JS code that I had written, and I am unable to find a solution to resolve it

Every time I attempt to run ng serve, the following error message pops up: "The serve command requires to be run in an Angular project, but a project definition could not be found." I've already experimented with various commands like: npm cache clean ...

Loop through every element in the Angular2 template

I am working with the following template and I need to access all the elements within it. Using ViewChildren only gives me a reference to one element, most likely because no two elements are the same and I am not using the same directive/component inside t ...

Using jQuery to transfer data via POST method

I'm currently working on integrating a third-party tool into our website. The tool requires the use of a form with the post method to send data to their site. Is there a way for me to replicate this action without relying on the form tag? I am not ver ...

Error occurs when attempting to read the 'map' properties of null because the JSON array is double nested

Within my code, I am attempting to access the URLs of two thumbnails in the JSON data below. Currently, I can only retrieve the information from the first array: <>{post.attributes.description}</> However, I am encountering difficulty retrievi ...

Button Vote in Bootstrap is unresponsive

I have a voting system implemented on my website using normal CSS buttons, and it works perfectly fine. However, when trying to integrate it with Bootstrap buttons, it seems to not function properly. I am looking to switch to using Bootstrap buttons for t ...

The replaceWith function in jQuery does not support <script> elements

I am faced with a situation where my AJAX response includes HTML code, including <script> elements. My goal is to replace an existing element with this HTML content. However, when I attempt to do so using the following code: $(element).replaceWith( ...

Exploring Angular's View Encapsulation with Third-Party Libraries

When I integrate an external component into my own, I face a challenge with styling due to Angular View Encapsulation. Any CSS I define in my component does not affect the external component used in my HTML template. To work around this issue, I have set e ...