Display only the labels of percentages that exceed 5% on the pie chart using Chart JS

I'm currently diving into web development along with learning Chart.js and pie charts. In my project, the pie chart I've created displays smaller percentage values that are hardly visible, resulting in a poor user experience on our website. How can I address this issue and eliminate the display of smaller percentages? Please see below for the code snippet where I generated the problematic pie chart; any guidance or assistance would be greatly appreciated. Thank you.

Edit: To clarify, when I mentioned showing only percentages greater than 5%, I mean that the percentage labels should be displayed only on sections representing more than 5% of the total data. Data points with less than 5% should still be included in the pie chart, but their corresponding percentage values should not be shown.

 

<!DOCTYPE html>
<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="27444f4655534d540a574b52404e490a434653464b4645424b54671709100917">[email protected]</a>"></script>
  </head>
  <body>
  <canvas id="myChart1" width="90" height="90" style="width:100%;max-width:650px"></canvas>
  <script>
        function getColors(length) {
        let pallet = ["#0074D9", "#FF4136", "#2ECC40", "#FF851B", "#7FDBFF", "#B10DC9", "#FFDC00", "#001f3f", "#39CCCC", "#01FF70", "#85144b", "#F012BE", "#3D9970", "#111111", "#AAAAAA"];
        let colors = [];
  
        for (let i = 0; i < length; i++) {
          colors.push(pallet[i % (pallet.length - 1)]);
        }
  
        return colors;
      }
      var xValues = ['Multimeter', 'UniBox', 'Toby', 'Cables', 'Test','nokia','samsung','Jio','honda'];
      var yValues = [2, 100, 223, 84, 197,3,8,7,50];
      var barColors = getColors(xValues.length);
      var ctx = document.getElementById("myChart1").getContext('2d');
     var myChart = new Chart(ctx, {
     type: 'pie',
     data: {
      labels: xValues,
      datasets: [{
        backgroundColor: barColors,
        data: yValues
      }]
     },
    options:{
      tooltips: {
        enabled: true
      },
      plugins: {
        datalabels: {
          formatter: (value, ctx) => {
    
            let sum = ctx.dataset._meta[0].total;
            let percentage = (value * 100 / sum).toFixed(2) + "%";
            return percentage;
    
    
          },
          color: '#fff',
        }
      },
      "legend": {
        "display": true,
        "labels": {
          "fontSize": 20,
        }
      },
      title: {
        display: true,
        fontColor: 'rgb(255, 0, 0)',
        fontSize: 25,
        text: "Current Inventory Received"
      }
    }
  });
  </script>
</body>

</html>

Answer №1

Make sure to adjust the formatter function so that it only returns a value if the percentage exceeds 5.

 <!DOCTYPE html>
<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e5868d8497918f96c8958990828c8bc881849184898487808996a5d5cbd2cbd5">[email protected]</a>"></script>
  </head>
  <body>
  <canvas id="myChart1" width="90" height="90" style="width:100%;max-width:650px"></canvas>
  <script>
        function getColors(length) {
        let pallet = ["#0074D9", "#FF4136", "#2ECC40", "#FF851B", "#7FDBFF", "#B10DC9", "#FFDC00", "#001f3f", "#39CCCC", "#01FF70", "#85144b", "#F012BE", "#3D9970", "#111111", "#AAAAAA"];
        let colors = [];
  
        for (let i = 0; i < length; i++) {
          colors.push(pallet[i % (pallet.length - 1)]);
        }
  
        return colors;
      }
      var xValues = ['Multimeter', 'UniBox', 'Toby', 'Cables', 'Test','nokia','samsung','Jio','honda'];
      var yValues = [2, 100, 223, 84, 197,3,8,7,50];
   
      var barColors = getColors(xValues.length);
      var ctx = document.getElementById("myChart1").getContext('2d');
     var myChart = new Chart(ctx, {
     type: 'pie',
     data: {
      labels: xValues,
      datasets: [{
        backgroundColor: barColors,
        data: yValues
      }]
     },
    options:{
      tooltips: {
        enabled: true
      },
      plugins: {
        datalabels: {
          formatter: (value, ctx) => {
    
            let sum = ctx.dataset._meta[0].total;
            let percentage = (value * 100 / sum).toFixed(2);
            return percentage > 5 ? percentage + "%" : "" ;
    
    
          },
          color: '#fff',
        }
      },
      "legend": {
        "display": true,
        "labels": {
          "fontSize": 20,
        }
      },
      title: {
        display: true,
        fontColor: 'rgb(255, 0, 0)',
        fontSize: 25,
        text: "Current Inventory Received"
      }
    }
  });
  
 
  </script>
</body>

</html>

Answer №2

To find the total and filter out values exceeding 5%, you can utilize the reduce method for calculation purposes followed by applying filter to identify percentages greater than 5%. Subsequently, feed the resultant array named result into a visualization chart.

let yValues = [2, 100, 223, 84, 197,3,8,7,50];
let sum = yValues.reduce((sum, item) => sum + item, 0)
let result = yValues.filter(value => {
    let percentage = ( value / sum ) * 100;
    if ( percentage > 5 ) return true;
    else false;
})

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

Passing large arrays of data between pages in PHP

I'm facing a challenge where I need to pass large arrays of data between pages. Here's the situation: Users input their Gmail login details in a form, which is then sent to an AJAX page for authentication and contact retrieval. If the login fail ...

What prevents Django websites from being embedded within another HTML (iframe)?

I attempted to include a Django form within another HTML page, but it's not functioning correctly. I've tried on several of my other Django sites with no success. I even tested it on other websites as well. Is there a restriction on using Django ...

Is it possible to share an .ics file using SparkPost in a Node.js environment?

Attempting to generate an i-cal event and link it to a sparkpost transmission in the following manner: const event = cal.createEvent({ start: req.body.a.start, end: req.body.a.end, summary: req.body.a.title, description: req.body.a.body, ...

Padding will not completely fill the <li> and <div> elements

Looking to create a sleek menu bar that's 40px tall and fills up 80% of the browser width. The challenge arises when trying to center the text within the menu items. Despite adjusting padding for alignment, there's still a small gap because of & ...

Tips for implementing a regular expression in JavaScript to parse tags from a Docker image?

I recently came across this regex for parsing docker image tag in Python. ^(?P<repository>[\w.\-_]+((?::\d+|)(?=/[a-z0-9._-]+/[a-z0-9._-]+))|)(?:/|)(?P<image>[a-z0-9.\-_]+(?:/[a-z0-9.\-_]+|))(:(?P<tag>[\w.&bs ...

What is the best way to include a background image in a div within a React component?

I'm currently following a tutorial on creating an RPG game using React. The tutorial can be found at this link. I am trying to replicate the presenter's code by typing it out myself. However, I'm running into an issue when attempting to add ...

Selecting a color in Vuetify's color picker triggers the @

I have incorporated the Vuetify color picker into my project for changing the background and text colors of elements. Currently, I am storing the hex color values in Firestore by using the @input="updateColor" attribute on the v-color-picker to t ...

Guidance on toggling elements visibility using Session Service in AngularJS

After reading this response, I attempted to create two directives that would control the visibility of elements for the user. angular.module('app.directives').directive('deny', ['SessionTool', function (SessionTool) { ret ...

How to Use Vanilla JavaScript to Fetch a JSON File, Convert the Data into an Array, and Iterate Through Each Object

Imagine having a JSON file called map.json: { "images":{ "background": ["images/mountains.png","images/sea.png"] } } The goal is for JavaScript to retrieve "images/mountains.png" from map.json and us ...

How to designate a default selection value using local array data source in Select2.js version 4.0?

If I am using the select2.js v4 plugin with a local array data source, how can I set the default selected value? For instance, consider the following code: var data_names = [{ id: 0, text: "Henri", }, { id: 1, text: "John", }, { id: 2, text: ...

Including additional data to a page after each iteration in order to display the current progress

I am currently working on a loop that iterates through the lines of a text area and processes each line sequentially. However, I am facing an issue where the page becomes unresponsive until all the data has been processed. Is there a way to dynamically u ...

The component fails to update even after changes are made to the Redux state

I currently have 4 buttons, each with a different color, and I want to display the last 10 button clicks as colors on 10 squares. The redux state is being used to map and display the square colors, which are also stored in localStorage. When a button is c ...

Tips for customizing the appearance of a jQuery sortable target list prior to dropping items

When using jquery sortable, I am able to customize a placeholder inside a connected list specified in the connectWith option to visualize where the content will be dropped. However, I am struggling to find a way to style the actual list that contains the p ...

Troubleshooting the inability to set percentage values in Bootstrap styling

My goal is to create a bar with thin bars, but my use of Bootstrap limits my control over sizes. <template> <div class="container-fluid mx-auto"> <div class="row"> <div class="square rounded-pill&qu ...

Setting the Datetimepicker to be used with every input field

I currently have four textboxes identified by their unique ids: title, sdate, edate, and pdate. My goal is to assign a Datetimepicker to the textboxes that contain the word 'date' in their id. This means I want the Datetimepicker to be assigned ...

Visualizing Data with d3.js Force Chart: Integrating Images with Nodes for Dynamic Animation

After enhancing a force diagram to compare two profiles, I am faced with the challenge of getting the main node to display an image. View comparison here How can I centrally align and size the image correctly while making the thumbnail data from the JSO ...

repeated firing of keydown event in ReactJS

Having an issue with adding an event listener and checking if it's level 1. When I press the space key once, it seems to fire more than 50 times. Any assistance would be greatly appreciated. document.addEventListener("keyup", function(e) { if(l ...

Efficiently passing parameters to AJAX URLs in Django

When trying to pass a parameter to the URL path to specify which user's role I want to change, I keep encountering an error. NoReverseMatch at /manageuser/ Reverse for 'editrole' with keyword arguments '{'user_name': &apo ...

Are you using yeoman with csslint in your project?

As a newcomer to grunt, I am facing challenges in integrating csslint to monitor my project while running "grunt serve" for csslinting. I am specifically struggling with disabling the adjoining classes warning since it is not relevant for IE6 compatibili ...

npm WARNING: The package @angular-devkit/[email protected] is in need of a peer dependency xxxx, however no installation for this dependency has

Attempting to launch an angular project and encountering the following errors: $ npm install npm WARN @angular-devkit/[email protected] requires a peer of @angular/compiler-cli@^14.0.0 but none is installed. You must install peer dependencies yoursel ...