Fix bars in Chart.js with long labels - Javascript Chart.js

Javascript examples for Chart.js:Bar Chart

Description

Fix bars in Chart.js with long labels

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>Chart.js v2 stacked bar chart</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script> 
      <script type="text/javascript">
window.onload=function(){/*from ww  w  .ja v a 2s.  com*/
  var numberWithCommas = function(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  };
var dataPack1 = [40, 47, 44, 38, 27];
var dataPack2 = [10, 12, 7, 5, 4];
var dataPack3 = [17, 11, 22, 18, 12];
var dates = [["Some l-o-o-o-o-", "o-o-o-o-o-o-o-", "n-n-n-n-n-n-g-g-g-", "g-g-g-g label"], "DDD", ["EEE", "FFF", "GGG"], "HHH", "III"];
var bar_ctx = document.getElementById('bar-chart');
var bar_chart = new Chart(bar_ctx, {
    type: 'bar',
    data: {
        labels: dates,
        datasets: [
        {
            label: 'Bad Style',
            data: dataPack1,
                  backgroundColor: "#512DA8",
                  hoverBackgroundColor: "#7E57C2",
                  hoverBorderWidth: 0
        },
        {
            label: 'Warning',
            data: dataPack2,
                  backgroundColor: "#FFA000",
                  hoverBackgroundColor: "#FFCA28",
                  hoverBorderWidth: 0
        },
        {
            label: 'Error',
            data: dataPack3,
                  backgroundColor: "#D32F2F",
                  hoverBackgroundColor: "#EF5350",
                  hoverBorderWidth: 0
        },
        ]
    },
    options: {
           animation: {
           duration: 10,
        },
        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}
    }
   }
);
    }

      </script> 
   </head> 
   <body> 
      <canvas id="bar-chart" width="600" height="350"></canvas>  
   </body>
</html>

Related Tutorials