bars Chart with long labels - Javascript Chart.js

Javascript examples for Chart.js:Bar Chart

Description

bars Chart 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(){/*  ww w  . j  ava2s. c  o  m*/
 // Return with commas in between
  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", "AAA", "BBB", "CCC", "DDDDDDDDD"];
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}
    },
    plugins: [{
    beforeInit: function (chart) {
      chart.data.labels.forEach(function (value, index, array) {
        var a = [];
        a.push(value.slice(0, 5));
        var i = 1;
        while(value.length > (i * 5)){
           a.push(value.slice(i * 5, (i + 1) * 5));
            i++;
        }
        array[index] = a;
      })
    }
  }]
   }
);
    }

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

Related Tutorials