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

History.pushState is not a function that I utilize in my work

Can anyone assist me with implementing the history.pushState jQuery code? I am struggling to get it to work and I don't have much knowledge on how to do it. Any help would be greatly appreciated. Here is the code I have so far... <!doctype html> ...

trigger a border hover effect on an HTML element

Is it possible to attach a mouseover event specifically to the left border of a div element in HTML? The div serves as a container for various other intricate HTML elements, each with their own mouseover events. While binding a mouseover event to the enti ...

Issue with ApexCharts Donut Chart legend labels not matching the specified data labels (stuck as 'series-1', etc.)

I'm trying to incorporate a simple donut chart from Apexcharts into my Vue.js project. However, despite following the guidelines provided on their website documentation, the legend titles are still displaying as 'series-1, series-2, ...'. T ...

The labels assigned to buttons will direct users to unique links specifically designated for that button

I've been working on a website to share some code I created, but my skills in HTML and CSS are not the best. Please forgive me if there are obvious mistakes. Here's the code I have so far: <!DOCTYPE html> <html> <head> ...

Adjust the font size in CSS based on a specified range of values

When the screen size is small (mobile), the font size is fixed at 14px. On really large screens, the font size is set to 18px, ensuring it never goes below 14px or above 18px>. This is achieved using media queries.</p> <p>However, for the i ...

The success notification transforms into a cancellation alert once the file has been successfully uploaded

I'm struggling to show the correct message after a file is successfully uploaded. Currently, when a file is successfully uploaded, the success message briefly displays but then quickly changes to the cancel message. I want the success message to rema ...

Striving to implement a dynamic expand and collapse animation feature for a card in ReactJS

I'm attempting to create an expand and collapse animation effect on a card without relying on bootstrap or any external libraries. I have tried adding a transition property but it doesn't seem to work when the button is clicked. Here is the comp ...

Express Angular Node Template Render throwing an error: module 'html' not found

I am currently in the process of creating a web application using AngularJS with ui-router for routing via $stateProvider, ensuring that only the specified states are displayed in the ui-view. In my server.js file, I have set up an initial framework such ...

Is it possible to include a callback function as a property in an object in React?

I need to include a callback function in a prop of type object. I have developed a custom component for a data table where I pass columns, data, and actions as props. The actions prop consists of an array of objects with handler callback functions linked ...

Experience the feeling of releasing momentum by click and dragging the scroll

One feature I am looking for is the ability to control the scroll speed when dragging, and have the scroll continue moving slightly after release instead of stopping instantly. CodePen: https://codepen.io/rKaiser/pen/qGomdR I can adjust the speed adequat ...

The attempt to connect with react-native-fetch-blob has not been successful

How do I resolve the issue of displaying a PDF from my assets folder in an Expo, React Native project using react-native-pdf? While scanning folders for symlinks, encountered an error with RNFetchBlob library in my project directory. The automatic linki ...

What is the best way to place two span elements beside each other?

Is there a way to align the name and address on the same line, with the address positioned on the right and the name on the left? Currently, the address is appearing on a separate line from the name. How can I resolve this issue? Here is the provided cod ...

What is the best way to trigger a snackbar notification when two passwords do not match?

I'm currently developing a full stack application and I am facing an issue with displaying a snackbar in my signup component when the user's password and confirm password do not match. I have been advised to pass the setOpenAlert method as props ...

A guide to implementing lazy loading using BXSlider

I have implemented an image gallery using Bxslider, but I am facing an issue with the loading time as there are more than 15 images in each slide. To address this problem, I want to load images one by one when a particular slide appears. I came across an e ...

Dynamic TextField sizing

I am currently facing an issue while displaying data on a webpage using TextField component from @material-ui. Each record of data has varying lengths, making most values appear unattractive (occupying only 10% of the textfield width). Even though I am ut ...

After running assets:install and assetic:dump, Font Awesome fonts are no longer functioning properly

Setting up a site on shared hosting has been going smoothly, except for the FontAwesome icons which Symfony is having trouble finding in their designated locations. The steps I followed to move the site to production on shared hosting are: To overcome th ...

The file upload issue with FormData append in CodeIgniter is causing errors

My current challenge involves uploading files using AJAX to my CodeIgniter based website. Unfortunately, I am encountering an issue where I cannot retrieve the file field value in the controller. This results in an error message stating "Undefined index: & ...

The problem arises when the body/html element is narrower than the browser window

I encountered a strange issue while working on a website for a client/design studio. Despite setting the body and html elements to a width of 100%, I noticed that when I resize the browser, a scrollbar appears forcing me to scroll right. Upon scrolling, I ...

"Troubleshooting the issue of null values in ASP.NET Core Razor Pages when using Ajax POST

I'm currently working on an ASP.NET (6.0) Razor Pages project where I am facing an issue with posting data using AJAX. Despite my efforts, the posted data always ends up being null. Even after going through similar questions on Stack Overflow, I have ...

Issues with expanding all nodes in the Angular Treeview function by Nick Perkins in London are causing difficulties

Currently utilizing the angular treeview project found here: https://github.com/nickperkinslondon/angular-bootstrap-nav-tree After examining the functionality, it seems that this treeview is lacking search capabilities. To address this limitation, I deci ...