Chart.js to Align time scale labels with the center of the bars - Javascript Chart.js

Javascript examples for Chart.js:Bar Chart

Description

Chart.js to Align time scale labels with the center of the bars

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){// w w  w .ja v  a2  s  .co  m
var barChartData = {
  labels: ["2015-01-01", "2015-02-01", "2015-03-01", "2015-04-01", "2015-05-01", "2015-07-01"],
  datasets: [{
    label: 'Dataset 1',
    backgroundColor: "rgba(220,220,220,0.5)",
    data: [10, 4, 5, 7, 2, 3]
  }]
};
var ctx = document.getElementById("canvas").getContext("2d");
new Chart(ctx, {
  type: 'bar',
  data: barChartData,
  options: {
    elements: {
      rectangle: {
        borderWidth: 2,
        borderColor: 'rgb(0, 255, 0)',
        borderSkipped: 'bottom'
      }
    },
    responsive: true,
    legend: {
      position: 'top',
    },
    title: {
      display: true,
      text: 'Chart.js Bar Chart'
    },
    scales: {
      xAxes: [{
        categoryPercentage: .5,
        barPercentage: 1,
        type: 'time',
        scaleLabel: {
          display: true,
          labelString: 'Year-Month'
        },
        time: {
          unit: 'month',
          displayFormats: {
            month: "MMM YY"
          }
        },
        gridLines: {
          offsetGridLines: false,
          drawTicks: true,
          display: true
        },
        stacked: true
      }],
      yAxes: [{
        ticks: {
          beginAtZero: true
        },
        stacked: true
      }]
    },
    animation: {
      onComplete: function() {
        var chartInstance = this.chart,
          ctx = chartInstance.ctx;
        ctx.font = Chart.helpers.fontString(10, "bold", Chart.defaults.global.defaultFontFamily);
        ctx.textAlign = 'center';
        ctx.textBaseline = 'center';
        this.data.datasets.forEach(function(dataset, i) {
          var meta = chartInstance.controller.getDatasetMeta(i);
          meta.data.forEach(function(bar, index) {
            var data = dataset.data[index];
            console.log(bar);
            if (data > 0) {
              ctx.fillText(data, bar._model.x, bar._model.base - (bar._model.base - bar._model.y) / 2 - 5);
            }
          });
        });
      }
    }
  }
});
    }

      </script> 
   </head> 
   <body> 
      <div id="container" style="width: 75%;"> 
         <canvas id="canvas"></canvas> 
      </div>  
   </body>
</html>

Related Tutorials