Enhance your horizontal stacked bar chart in chart.js by incorporating inner labels with the help of the 'chartjs-plugin-labels' plugin

Currently, I have integrated a package that allows me to incorporate labels into my charts -

import * as pluginDataLabels from "chartjs-plugin-labels";

While it works perfectly fine with line charts, pie charts, and normal bar charts, I am facing an issue with displaying labels on my stacked bar chart. Below is the code snippet:

  public stackedChartLabels = ["Test 1"];
  public stackedChartPlugins = [pluginDataLabels];
  public stackedChartData = [
    {
      label: "Low",
      data: [67.8],
      backgroundColor: "#D6E9C6", // green
      stack: "a",
    },
    {
      label: "Moderate",
      data: [20.7],
      backgroundColor: "#FAEBCC", // yellow
      stack: "a",
    },
    {
      label: "High",
      data: [11.4],
      backgroundColor: "#EBCCD1", // red
      stack: "a",
    },
  ];
  public stackedChartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      labels: [
        {
          render: function (args) {
            return args.value;
          },
          position: "inside",
          fontColor: "#023d7d",
          fontSize: 12,
        },
      ],
    },
    scales: {
      yAxes: [
        {
          ticks: {
            fontSize: 12,
            fontColor: "#023d7d",
          },
        },
      ],
      xAxes: [
        {
          ticks: {
            min: 0,
            max: 100,
            fontSize: 12,
            fontColor: "#023d7d",
            precision: 0,
          },
        },
      ],
    },
  };

And here is the corresponding HTML code:

<canvas
              baseChart
              [datasets]="stackedChartData"
              [labels]="stackedChartLabels"
              [chartType]="'horizontalBar'"
              [legend]="false"
              [plugins]="stackedChartPlugins"
              [options]="stackedChartOptions"
              height="150"
            >
            </canvas>

I'm seeking assistance in resolving the issue of not being able to display labels on my stacked bar chart. The objective is to showcase the value on each segment accurately.

Answer №1

This piece of code successfully resolved the issue:

animation: {
      duration: 1000,
      onComplete() {
        let chartInstance = this.chart;
        let ctx = chartInstance.ctx;
        ctx.textAlign = "end";
        ctx.textBaseline = "middle";
        ctx.fillStyle = "#fff";
        ctx.font = "10px sans-serif";
        this.data.datasets.forEach(function (dataset, i) {
          var label = dataset.label;
          var meta = chartInstance.controller.getDatasetMeta(i);
          meta.data.forEach(function (bar, index) {
            var data = dataset.data[index];
            if (label.indexOf("%") >= 0) data += "%";
            ctx.fillText(data + "%", bar._model.x, bar._model.y);
          });
        });
      },
    },

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

Discover results while inputting in the search box

Can anyone assist me? I'm looking to enhance my current code by adding a search functionality to the ul list. I want users to be able to type in a search term and have the matches automatically highlighted as they type, similar to a "find-as-you-type ...

Disable event listener when the controls are unlocked using the pointerlock controls in three.js

While navigating a model with threejs pointerlock controls, clicking on specific sections of the model directs users to different parts of the site. However, an issue arises when the camera is centered over a section and the user exits the pointerlock. Upo ...

Saving fonts when deploying on Vercel with Next.js is not supported

Troubleshooting Differences in Local Viewing and Deployment: https://i.stack.imgur.com/jktPN.png When viewing locally, everything appears as expected. However, upon deploying, there are noticeable discrepancies. https://i.stack.imgur.com/NKQQ6.png Even ...

Syntax error: Your code encountered an unexpected closing curly brace

Here is the code snippet I am working with: <?php session_start();?> <!DOCTYPE html> <html> <head> <title>Narcis Bet</title> <meta charset="utf-8"> <link rel="stylesheet" href="css/style.css" type="text/css"&g ...

I want to use React Bootstrap and Next.js to retrieve the text from a textbox in a React Component and then send it back to my Index.js file. How can I accomplish this task?

I need some assistance. Currently, I am facing a challenge. I am trying to retrieve data from one of my React Components named ParameterList. This component contains a React-Bootstrap Form.Control element for numerical input. My goal is to take the value ...

Loading Disqus comments dynamically upon clicking a button within a Next.js application

After noticing a significant decrease in page performance scores due to Disqus comments embedded on Vercel Analytics, I am considering implementing a "Load comments" button instead of loading the actual comments onClick. I have been using the disqus-react ...

Is Socket.io exclusive to browsers?

Similar Question: Using socket.io standalone without node.js How to run socket.io (client side only) on apache server My website is hosted on a Linux server with shared hosting. Since I don't have the ability to install node.js, I am looking ...

How should I start working on coding these sliders?

Which programming language should I use? My understanding of Java Script is limited, so coding them on my own might be challenging. What would be the essential code to begin with? Here are the sliders - currently just Photoshop images... ...

What's the best way to ensure uniform card height in Material-UI?

Is there a way to ensure consistent card height in Material-UI without setting a fixed height? I want the card heights to dynamically adjust based on content, with all cards matching the tallest one on the website. How can this be achieved while also addin ...

Adjust the size of an image within a canvas while maintaining its resolution

My current project involves using a canvas to resize images client-side before uploading to the server. maxWidth = 500; maxHeight = 500; //handle resizing if (image.width >= image.height) { var ratio = 1 / (image.width / maxWidth); } else { var ...

Removing an object from an array when a certain key value already exists in TypeScript

I'm currently facing an issue with my function that adds objects to an array. The problem arises when a key value already exists in the array - it still gets added again, but I want it to only add if it doesn't exist yet. Here's what I have: ...

Resolving Uncaught ReferenceError: require is not defined - Learn the solution here!

While working on my electron app, I encountered the error message Uncaught ReferenceError: require is not defined This is the relevant section of my code: const remote = require('electron').remote var minimise = document.getElementById('mi ...

Sending form data to the server using JavaScript: A step-by-step guide

Currently, I am dealing with the configuration of two servers. One server is running on React at address http://localhost:3000/contact, while the other is powered by Express at address http://localhost:5000/. My goal is to transmit form data as an object v ...

Add the bannercode snippet found on a webpage

I am currently facing an issue with appending a banner code to the end of a URL. The scenario is as follows: An individual receives an email with a link to a website (SITE1), where the URL includes a banner code, such as www.site1.com?banner=helloworld O ...

Align both the image and text in the center with no space between

How can I center two blocks containing both images and text vertically and horizontally while using flexbox? I notice that when the text is longer, padding appears between the image and the text. How can I remove this padding?1 .product-teaser { width ...

AngularJS Skype URI Button Problem

Implementing a Skype button in my project using AngularJS has been challenging. Here is the code I am currently working with: HTML: <script type="text/javascript" src="http://www.skypeassets.com/i/scom/js/skype-uri.js"></script> <skype-ui ...

Creating an overlay with CSS hover on a separate element and the ::before pseudo class

Issue: I am struggling to display the overlay when hovering over the circle element, rather than just the image itself. I have attempted to achieve this using CSS, but can't seem to make it work as intended. Any guidance and examples using JavaScript ...

Struggling with implementing click events on Ionic-Calendar 2?

Attempting to implement a (click) event for ionic-calendar 2 where it deactivates a button if the user clicks on a date that has already passed. The issue I am facing is that when I initially click on a past date, the button remains enabled. However, upon ...

Is there a way to invoke a JavaScript function specifically for a given link?

I am trying to make the JavaScript only apply to a specific A LINK (#tornado,_bar -> ul -> li -> a links) when clicked, but it is applying to all A links. How can I specify the particular link in the JS? The JavaScript code is not functioning cor ...

Issues arise with AJAX authentication request

Currently, I'm working on incorporating a basic login form with an AJAX request that forwards the user to a page for querying my database. Depending on the results, the user is then redirected to the main index page or prompted back to the login form. ...