[Chartjs]-Chart.js v2: Align time scale labels with the center of the bars

0👍

This fiddle may help to place the data label in the center of the bar
https://jsfiddle.net/tea8dhgy/

<div id="container" style="width: 75%;">
  <canvas id="canvas"></canvas>
</div>       
 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: {
              // min: '2014-12-01' ,
              // max: '2015-12-01',
              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];
                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);
                }
              });
            });
          }
        }
      }
    });

-1👍

I was able to get a working chart by removing the min and max values set.

Here is the JSFiddle

Was the following image the desired outcome?

enter image description here

Leave a comment