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>

https://i.sstatic.net/wt92m.png

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

Tips for assigning a personalized value to an MUI Switch when it is in the off position

I am currently utilizing the MUI Switch component to create an On-Off button. I have manually set the value as "on" and it is functioning correctly when the switch is in the true state. However, there doesn't seem to be an option to change the default ...

Leveraging the power of the jQuery load function alongside HTML forms in web

Currently in the process of creating a fresh website and considering implementing jQuery's load() function to bring content from various html pages into my main page. load() is functioning smoothly. Below is my current code: Main.html page where cont ...

substituting symbols with colorful divs

I'm looking to add some color to my text using specific symbols. (), ||, and ++ are the symbols I'm using. If a text is enclosed in | symbols, it will appear in blue, and so on... Here is the code in action: const text = "|Working on the| i ...

The CORS policy has blocked access to XMLHttpRequest from 'localhost' to 'localhost'. A preflight response is required

I'm encountering the following error message: Access to XMLHttpRequest at 'https://localhost:44355/Brand' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access ...

Isn't AJAX all about the same origin policy?

Despite my confusion surrounding the same domain origin policy and jQuery AJAX, I have noticed that when I make a GET request to a URL using jQuery, I am able to successfully retrieve the results. This goes against what I understood about the restriction ...

Error: The variable "$this" has not been defined in the AJAX function

Recently, I've been delving into the world of javascript and ajax. I'm trying to create a dynamic select option list similar to this: https://i.sstatic.net/qELIf.png However, when attempting to compile using Google Chrome Developer tools (F12), ...

Limit the jQuery dialogue button to just one click

My goal is to create a jQuery dialogue box that sends data when the 'OK' button is clicked. The challenge I'm facing is making sure it only sends the data once, regardless of how many times the button is clicked. $.dialogue({ ...

Optimizing Three.js for better performance

Recently, I delved into working with three.js and webgl for a personal project. My goal was to develop a wardrobe model based on user input. You can check out the project at this link: Initially, the rendering speed was fast and smooth without Materials a ...

Using Jquery Simplyscroll to incorporate images on both the left and right side within a container or clip

I am currently utilizing Jquery Simplyscroll (http://logicbox.net/jquery/simplyscroll/) and I am seeking a way to incorporate a faded png image on both the left and right sides to prevent my images from appearing "cut off" while sliding through. Below is ...

The behavior of the jQuery click function seems to be quirky and not functioning as expected. Additionally, the

It seems that instead of triggering a POST request, somehow a GET request is being triggered. Additionally, the ajax call is not being made as expected. I have attempted this many times before, but none of my attempts seem to be working. It could potenti ...

What is the best way to add elements to an array that has not been globally initialized as an empty array?

Let's say I have a variable called, let Info and an array like this one, let arr1 = [4,5,6] I need to add the elements from arr1 into Info as an array, Here is what I attempted, for(let i =0;i<arr1.length;i++){ Info = [] Info = Info.push ...

When making a POST request from the client-side JavaScript, the req.body is coming back as an empty

I have been encountering several questions related to the same topic, but unfortunately, none of them have resolved my issue. Hence, I am posting a new question here. My objective is to send a POST request from client-side javascript to the Backend using ...

Styling with CSS or using tables: What should you choose?

Is there a way to replicate the frame=void functionality in CSS, or will I need to manually add frame=void to each table I create in the future? <table border=1 rules=all frame=void> I attempted to search for a solution online, but unfortunately, m ...

What is the process for including CSS in the .ashx.cs code-behind file in ASP.NET?

How can I insert a css class in the .ashx file while the .aspx UI page displays it as a string? What is the method to include css in the code behind of the .ashx page? I would like the text "Cook" to be displayed in red. Problem: https://i.sstatic.net ...

What is the term used for a tag that automatically closes itself?

Within tag-based languages such as HTML or XML, there are tags that automatically close themselves without the need for a separate closing tag: <tag/> As opposed to the traditional method of closing tags like this: <tag></tag> Do thes ...

What could be causing the calendar icon to not display in the table cell?

I've been working with the Bootstrap date picker inside a table, and I'm having trouble getting the date picker icon to display using the fas fa-calendar-alt css class. <td> <input type="text" id="expirydate{{$index}} ...

The ngOnChanges method fails to exhibit the anticipated modifications in a variable

Trying to grasp the concept of the ngOnChanges() callback, I created an example below. Despite having values for the attributes title and content in the Post interface during compile time, I do not see any logs from ngOnChanges. Please advise on the corre ...

The error message "TypeError: usert.addItem is not a function" indicates that

Currently in the process of developing a discord bot using discord.js, sequelize, and sqlite for database management. Encountering an issue with a custom function that is not being recognized as defined by the terminal, despite me confirming its definition ...

Is it possible for the vertical borders of <span> to overlap?

When nesting multiple spans within each other and giving them borders, their horizontal borders overlap by default while their vertical borders stack. Check out a live example on JsFiddle: https://jsfiddle.net/4un9tnxy/ .html: <span><span>a& ...

Is it necessary to incorporate express in a Next.js project?

I'm currently working on a website using Next.js. With Next.js, I have access to features like SSR and dynamic routing. Is it necessary for me to incorporate express into my project? If yes, what are the reasons behind needing to use it? What unique ...