I'm having trouble seeing the values displayed above the bars in Chart.js

Recently, I started learning about chart.js and encountered an issue where the bars were not displaying the values on top, along with a question on how to add a percentage sign after the value. I'm using chart.js version 3.3.2 from a CDN. Any assistance would be greatly appreciated.

let myChart = document.getElementById('myChart').getContext('2d');
const label = ['A','B','C','D','E'];
const datas = [85, 90, 53, 100, 76];
const backgroundColors = [
    'rgba(255, 99, 132, 0.2)',
    'rgba(54, 162, 235, 0.2)',
    'rgba(255, 206, 86, 0.2)',
    'rgba(75, 192, 192, 0.2)',
    'rgba(153, 102, 255, 0.2)'
];
const borderColors = [
    'rgba(255, 99, 132, 1)',
    'rgba(54, 162, 235, 1)',
    'rgba(255, 206, 86, 1)',
    'rgba(75, 192, 192, 1)',
    'rgba(153, 102, 255, 1)'
]

let iChart = new Chart(myChart, {
    type: 'bar',
    data: {
        labels: label,
        datasets: [{
            label: 'EQA-Übereinstimmung',
            data: datas,
            backgroundColor: backgroundColors,
            borderColor: borderColors,
            borderWidth: 1
        }]
    },
    options: {
        responsive:true,
        maintainAspectRatio: false,
        animation: {
            duration: 1,
            onComplete: function () {
                var chartInstance = this.chart,
                    myChart = chartInstance.myChart;
                    myChart.textAlign = 'center';
                    myChart.fillStyle = "rgba(0, 0, 0, 1)";
                    myChart.textBaseline = 'bottom';
                    // Loop through each data in the datasets
                    this.data.datasets.forEach(function (dataset, i) {
                        var meta = chartInstance.controller.getDatasetMeta(i);
                        meta.data.forEach(function (bar, index) {
                            var data = dataset.data[index];
                            myChart.fillText(data, bar._model.x, bar._model.y - 5);
                        });
                    });
            }
        }
            
    }
});

Any insights on why this is happening?

Answer №1

The code needed a little update as it was a bit outdated. Adding a percentage sign to the value can be achieved by using string interpolation with the fillText method.

Here's a working sample:

let myChart = document.getElementById('chartJSContainer').getContext('2d');
const label = ['A', 'B', 'C', 'D', 'E'];
const datas = [85, 90, 53, 100, 76];
const backgroundColors = [
  'rgba(255, 99, 132, 0.2)',
  'rgba(54, 162, 235, 0.2)',
  'rgba(255, 206, 86, 0.2)',
  'rgba(75, 192, 192, 0.2)',
  'rgba(153, 102, 255, 0.2)'
];
const borderColors = [
  'rgba(255, 99, 132, 1)',
  'rgba(54, 162, 235, 1)',
  'rgba(255, 206, 86, 1)',
  'rgba(75, 192, 192, 1)',
  'rgba(153, 102, 255, 1)'
]

let iChart = new Chart(myChart, {
  type: 'bar',
  data: {
    labels: label,
    datasets: [{
      label: 'EQA-Übereinstimmung',
      data: datas,
      backgroundColor: backgroundColors,
      borderColor: borderColors,
      borderWidth: 1
    }]
  },
  options: {
    responsive: true,
    maintainAspectRatio: false,
    animation: {
      duration: 1,
      onComplete:  (x) => {
        const chart = x.chart;
        var { ctx } = chart;
        ctx.textAlign = 'center';
        ctx.fillStyle = "rgba(0, 0, 0, 1)";
        ctx.textBaseline = 'bottom';
        // Loop through each data in the datasets
        const metaFunc = this.getDatasetMeta;
        chart.data.datasets.forEach((dataset, i) => {
          var meta = chart.getDatasetMeta(i);
          meta.data.forEach((bar, index) => {
            var data = dataset.data[index];
            ctx.fillText(`${data}%`, bar.x, bar.y - 5);
          });
        });
      }
    }

  }
});
<body>
    <canvas id="chartJSContainer" width="600" height="400></canvas>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.3.2/chart.js"></script>
</body>

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 the duration of a background in jQuery

jQuery(document).ready(function(){ jQuery('div').css('background-color','#ffffff').delay(12000).css('background-color','#000000'); }); Hello everyone! I'm having some trouble with this code. I am ...

The xModal window will only pop up once, after which a page refresh is required

My modal window opens when a user clicks on a div, but I'm having an issue. The modal window doesn't reopen when I click on the div again. Here is my code: <div onclick="document.getElementById('id01').style.display='block&apos ...

Tips on separating a function into two separate files in Node.js

Hey there! I am just starting to explore Node.js so bear with me if I make any mistakes. So, I have this file: exports.Client = function() { this.example = function(name, callback) { console.log(name); }; ...

Troubleshooting Issues with Passing Values in jQuery AJAX POST Requests

Currently, I am working on two basic PHP pages: notification.php <html> <head><title></title> <meta charset="UTF-8"> <script src="https://cdn.firebase.com/js/client/2.4.2/firebase.js"></script> <script src="ht ...

What could be causing my onscroll function to cut off before reaching the end of the element?

Struggling with a function I created to slide a div horizontally into view in the center of a vertically scrolling page. It seems to work well under normal conditions, but when the page is scrolled quickly, it sometimes fails to complete the horizontal mov ...

Ways to choose an element when all classes are identical but the text content varies?

I'm looking to automate the website, specifically by selecting the Widgets section and clicking on it. The issue is that all the cards have the same class name, only the text inside them differs. I tried using this code snippet: get getWidgetButton() ...

What is the best approach for managing client-side routes when a page refresh displays the backend Rails route instead?

After deploying my SPA to Render, I encountered an issue. My application comprises a React frontend with Redux and a Rails backend. When the app initializes, it correctly displays the frontend route in the browser. Subsequent navigation without refreshing ...

Discovering the parameters at your disposal within a callback function can be easily achieved in JavaScript and MongoDB

Being new to JavaScript and web development, I've been self-studying but have encountered many roadblocks. Currently, I'm struggling with understanding functions with callback functions and their parameters. The documentation I've read so f ...

Using Angular $resource to store an object with arrays

Consider a scenario where we have a User $resource structured as follows: $scope.user = { name: 'John', hobbies: [1, 2, 3] } If we were to save User.save($scope.user) to the server, it would send the following parameters: name: 'John& ...

Each div will display the same image twice when loading the image

I have a grid where images are dynamically loaded with a link to a lightbox. Currently, this is how I am achieving it: $(".selection_thumb").each( function(i) { $(this).append("<a data-lightbox='image-1' href='img/folder/folder/"+(++ ...

Ways to retrieve a specific Array[property] within an object?

I am struggling to access a specific property within an array of objects. My goal is to extract the "name" elements from the app catalog array, combine them with the names from the custom array apps.name, and assign the result to a new property in the ques ...

Efficiently encode and decode JSON data between PHP and JavaScript

I am attempting to convert my array results into JSON format and then transmit them to an AJAX success event using JavaScript. PHP $results = array( "time1" => 1, "time2" => 2, ); echo json_encode($results); JAVASCRIPT ...

Updating an iframe's content URL

I am currently working on building a website using Google Web Design and everything is going well so far. I have added an iFrame to the site and now I am trying to figure out how to change its source when a button is pressed. Most of the information I fo ...

Every time I try to set up the MailChimp pop-up javascript, I encounter an Uncaught Error message saying that Bootstrap tooltips need Tether and an Uncaught ReferenceError message

Utilizing Wordpress and Understrap. Upon inserting the following code: <script type="text/javascript" src="//downloads.mailchimp.com/js/signup- forms/popup/embed.js" data-dojo-config="usePlainJson: true, isDebug: false"> </script><script ty ...

Issue encountered while serializing the `.product` object retrieved from the `getStaticProps` function in NextJS, in conjunction with

I ran into an error message saying "Error: Error serializing .product returned from getStaticProps in "/products/[id]". Reason: undefined cannot be serialized as JSON. Please use null or omit this value." This issue occurred while I was attempting to crea ...

I'm encountering inexplicable duplications of elements on my Wordpress site

Here is an example of my template header: <header> <?php if ( function_exists( 'jetpack_the_site_logo' ) ) jetpack_the_site_logo(); ?> <a class="menu-toggle">menu</div> <?php wp_nav_menu( array('them ...

Trouble with closing Bootstrap 4 modal

My Bootstrap 4 modal is causing issues as it pops up on button click but won't close unless I refresh the page. I've been attempting to get it to close by clicking the 'close' button or simply by clicking anywhere on the main page body. ...

Having trouble accessing information from Firebase Realtime Database within a React Native application

I am currently developing a React Native application that interacts with a Firebase database for reading and writing data. I have configured my Firebase permissions to allow read and write access: { "rules": { ".read": true, ...

The data in my JSON string is not fully received through the HTTP GET request

Whenever I send my array to the PHP file, it receives incomplete data. The content of my 'arr' variable is as follows: [["╪▒┘à┘╛┘╪د","67126881188552864","Empty,Empty,Empty,Empty,8644,-360,-4,8691,-3.48,-313,1015,4.334 M,1392/12/2 ...

Attempting to create a slider utilizing jQuery

I'm currently working on creating a slider using jquery. I have downloaded the cycle plugin for the slider and included it in my file. The slider consists of 7 pictures. Below is the code I am using, can someone please help me identify any issues? &l ...