How can you showcase individual values within a stacked bar chart on Chart.js?

Having trouble displaying values inside bars using Chart.js library for stacked bars. Currently, the values are shown above the bars, but I need them inside the bars. Here is the code snippet:

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

The code displays numbers on top of the bars, but I want them inside the bars. Here's the code snippet:

var numberWithCommas = function(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  };

var dataPack1 = [50000, 22000, 26000, 35000, 55000, 55000, 56000, 59000, 60000, 61000, 60100, 62000];

var dataPack2 = [0, 6000, 13000, 14000, 50060, 20030, 20070, 35000, 41000, 4020, 40030, 70050];

var dates = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

// Chart.defaults.global.elements.rectangle.backgroundColor = '#FF0000';

var bar_ctx = document.getElementById('bar-chart');
var bar_chart = new Chart(bar_ctx, {
    type: 'bar',
    data: {
        labels: dates,
        datasets: [
        {
            label: 'SoftEnterprises, Sales',
            data: dataPack1,
backgroundColor: "rgba(55, 160, 225, 0.7)",
hoverBackgroundColor: "rgba(55, 160, 225, 0.7)",
hoverBorderWidth: 2,
hoverBorderColor: 'lightgrey'
        },
        {
            label: 'SmartSystems, Sales',
            data: dataPack2,
backgroundColor: "rgba(225, 58, 55, 0.7)",
hoverBackgroundColor: "rgba(225, 58, 55, 0.7)",
hoverBorderWidth: 2,
hoverBorderColor: 'lightgrey'
        },
        ]
    },
    options: {
     animation: {
        duration: 10,
          onComplete: function(){
                var chartInstance = this.chart,
                ctx = chartInstance.ctx;
                ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
                ctx.textAlign = 'center';
                ctx.textBaseline = 'bottom';
                ctx.fillStyle = '#000';
                                this.data.datasets.forEach(function(dataset, i) {
                var isHidden = dataset._meta[0].hidden; //'hidden' property of dataset
                if (!isHidden) { //if dataset is not hidden
                    var meta = chartInstance.controller.getDatasetMeta(i);
                    meta.data.forEach(function(bar, index) {
                    var data = dataset.data[index];
                    ctx.fillText(data, bar._model.x, bar._model.y - 5);
                });
               }
            });
          
          }
        },
        tooltips: {
mode: 'label',
          callbacks: {
          label: function(tooltipItem, data) { 
          return data.datasets[tooltipItem.datasetIndex].label + ": " + numberWithCommas(tooltipItem.yLabel);
          }
          }
         },
        scales: {
          xAxes: [{ 
          stacked: true, 
            gridLines: { display: false },
            }],
          yAxes: [{ 
          stacked: true, 
            ticks: {
        callback: function(value) { return numberWithCommas(value); 
              },
            }, 
            }],
        }, // scales
        legend: {display: true}
    } // options
   },
   
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>

<canvas id="bar-chart" width="600" height="350"></canvas>

Answer №1

If you're looking to easily integrate value labels into stacked bars using Chart.js, the chartjs-plugin-datalabels is the ideal solution. Simply specify the following minimum options for the plugin to showcase values at the center of the stacked bars:

options: { //your chart options
   plugins: {
      datalabels: {
         display: true,
         align: 'center',
         anchor: 'center'
      }
   }
}

For more extensive customization of these values/labels within the bars, explore additional options available here.

Example in action ⧩

var numberWithCommas = function(x) {
   return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

var dataPack1 = [50000, 22000, 26000, 35000, 55000, 55000, 56000, 59000, 60000, 61000, 60100, 62000];

var dataPack2 = [0, 6000, 13000, 14000, 50060, 20030, 20070, 35000, 41000, 4020, 40030, 70050];

var dates = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

var bar_ctx = document.getElementById('bar-chart');
var bar_chart = new Chart(bar_ctx, {
   type: 'bar',
   data: {
      labels: dates,
      datasets: [{
         label: 'SoftEnterprises, Sales',
         data: dataPack1,
         backgroundColor: "rgba(55, 160, 225, 0.7)",
         hoverBackgroundColor: "rgba(55, 160, 225, 0.7)",
         hoverBorderWidth: 2,
         hoverBorderColor: 'lightgrey'
      }, {
         label: 'SmartSystems, Sales',
         data: dataPack2,
         backgroundColor: "rgba(225, 58, 55, 0.7)",
         hoverBackgroundColor: "rgba(225, 58, 55, 0.7)",
         hoverBorderWidth: 2,
         hoverBorderColor: 'lightgrey'
      }, ]
   },
   options: {
      tooltips: {
         mode: 'label',
         callbacks: {
            label: function(tooltipItem, data) {
               return data.datasets[tooltipItem.datasetIndex].label + ": " + numberWithCommas(tooltipItem.yLabel);
            }
         }
      },
      scales: {
         xAxes: [{
            stacked: true,
            gridLines: {
               display: false
            },
         }],
         yAxes: [{
            stacked: true,
            ticks: {
               callback: function(value) {
                  return numberWithCommas(value);
               },
            },
         }],
      },
      legend: {
         display: true
      },
      plugins: {
         datalabels: {
            display: true,
            align: 'center',
            anchor: 'center'
         }
      }
   }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>

<canvas id="bar-chart" width="600" height="350"></canvas>

Answer №2

The solution previously recommended is no longer effective with the most recent versions of Chart.js and chartjs-plugin-datalabels.

If you are working with Chart.js v3.7.0 or later and chartjs-plugin-datalabels v2.2.0 or later, follow the steps below to register it:

Register the plugin for all charts:

Chart.register(ChartDataLabels);

OR register it for specific charts only:

 var chart = new Chart(ctx, {
      plugins: [ChartDataLabels],
      options: {
        // ...
      }
    })

Please note that the plugin should not be nested within the chart options as suggested in the previous advice.

For further information, visit:

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

Include a property in the selected div

jQuery(document).ready(filter); function filter() { jQuery(".my-divs").each(function () { jQuery(".my-divs div").filter(function () { jQuery(this).toggle(jQuery(this).text() <= 3); }); }); jQuery(".my-divs div" ...

The wordpress jquery dependency is failing to respond

After converting an HTML ecommerce template into WooCommerce, I am experiencing issues with the functionality. The Nivo slider and some other product features are not working properly. It seems like they are having trouble finding WordPress jQuery, even th ...

Displaying country-specific API details (such as capital and currency) in a card container when selecting a country from a dropdown menu

My objective is to display the card information for South Africa as the default value, even before entering any country's name into the search bar input field or selecting a specific country from the provided list. I am utilizing the restcountries API ...

Is it possible to target elements based on a specific CSS3 property they use?

Is there a method to target all elements in the DOM with a border-radius other than 0? If anyone has suggestions, it would be greatly appreciated! ...

What is the reason that the 'mouseenter' event only applies to the initial element in each round of iteration within a spacebar loop?

My goal is to create an off-canvas menu within a template component. I found inspiration from this helpful article. The setup I have is quite common: A container tab where I loop through an items collection An item component that contains the off-canvas ...

Accessing variables from child controllers with populated select inputs in Angular

I'm currently facing an issue involving 3 controllers: Parent Controller: DocumentController Child Controller1: XdataController Child Controller2: CompanyController The child controllers are used to populate data in three Selector inputs on the fron ...

Having trouble with jest mocking a function - it's not functioning as expected

I decided to create a simple test using jest to simulate a date change function. Here is the code snippet: import React from 'react'; import '@testing-library/jest-dom'; import { render, screen } from '@testing-library/react' ...

Transmitting JSON Web Tokens from AngularJS to Node.js

A situation has arisen where an AngularJS app must pass a JWT to the Node.js instance that is serving it. The Node.js instance has a /user route which will provide a JWT to the Angular client. What specific modifications should be implemented in the exist ...

Interested in leveraging string functions on the information retrieved from the API?

I am trying to utilize String functions such as slice(x,y), length() on the data received from the API. To achieve this, I first converted the data to a variable called mystr using JSON.stringify(obj), but encountered an issue where the console displayed: ...

Looking to add a dropdown feature to my current main navigation bar

I've been struggling to add a drop-down menu to my website's main menu. Every time I try, something goes wrong - sometimes the menu appears inline, other times it completely messes up the layout. Here is the HTML code snippet: <ul class="m ...

Encountering a non-constructor error while trying to import packages in React Typescript

I am currently working on a project that utilizes React with Typescript. While attempting to import a package, I encountered an error stating that the package lacks a constructor when I run the file. This issue seems to be prevalent in various packages, a ...

Troubleshooting issue with Express.json() functionality in the latest release of version 4.17

I'm currently exploring the MEAN stack and I am focused on performing CRUD operations. However, when I send data in the request body from Angular to the server, I end up receiving an empty request body. I'm unsure of where I might be making a mis ...

Tips for injecting animation into a DIV

I am trying to make a <div> element on my webpage expand to the full width and height of the screen. While I have managed to achieve this, I also want to implement an animation that will be displayed when the <div> enlarges to fit the screen si ...

Ways to position an image in the middle of a Div

I am currently working with PHP and Smarty, attempting to display a slideshow's images in the center of a specific div, but I am encountering difficulties achieving this. Below you will find the code snippet. Can anyone help me figure out what I migh ...

The discrepancy in the array leads to a result of either 1 or an undetermined

Array x = [3,5,7,9,1] Array y = [3,7,8] z = x - y this should result in z = [5,9,1] (7 is common but I want it excluded) Below is the code snippet: function arrayDifference(x, y) { var arr = []; var difference = []; for (var i = 0; i<x.length& ...

Retrieving chosen row data in Angular 6 Material Table

I am attempting to send the value of a selected row from one component to another upon clicking a button. However, in this particular example, I'm unsure where to obtain the selected row values and how to pass them on button click. After that, routing ...

Sending a request to a JSON file using Ajax

I have 2 questions: 1. I am trying to run this file, but it is not giving any errors or showing results. Please help me identify the problem. 2. I added a dropdown menu in my HTML file, but I'm unsure how to use it to display a list of names. Any sugg ...

Attempting to replicate the action of pressing a button using Greasemonkey

I am currently working on a greasemonkey script to automate inventory updates for a group of items directly in the browser. I have successfully implemented autofill for the necessary forms, but I am facing challenges with simulating a click on the submissi ...

Utilizing JQuery to update the selected item in a menu

Hey there! I'm currently using the jquery chosen plugin and I'm trying to make it so that I can select a menu value based on the selection from another select menu. Unfortunately, my code only works with a simple select menu and I need it to work ...

Learn how to effectively showcase various components by leveraging the new react-router-dom v6.0.0 alongside react-redux

My issue is that when I click on a link to render different components, the URL updates but the UI remains unchanged. No matter which item I click on to render, the same thing happens. I've tried numerous solutions to fix this problem without success. ...