Chartjs-ChartJS: How to center monthly bars against a daily line chart?

1👍

Welcome to Stackoverflow!

It seems that there is a way better than using the 15th of the month.

You need to add another axis for the bar that is a category type axis. Also its pretty critical that you have "offset: true" on that axis as well. Otherwise it will not center.

In the code below I named that category "bar" and the existing one "line"

I also created a fiddle: https://jsfiddle.net/jyf8ax3e/

var myChart = new Chart(ctx, {
  type: "bar",
  data: {
    labels: ["2017-08", "2017-09", "2017-10", "2017-11"],
    datasets: [
      {
        barPercentage: .7,
        xAxisID: "bar",
        label: "sales",
        data: monthlyTotal,
        backgroundColor: "green",
        borderColor: "black",
        borderWidth: 1,
        width: 55,
        order: 2,
      },
      {
        label: "stock",
        type: "line",
        data: dailyStock,
        backgroundColor: "orange",
        borderColor: "orange",
        fill: false,
        order: 1,
      },
    ],
  },
  options: {
    scales: {
      xAxes: [
        {
            id: "line",
          type: "time",
          time: {
            unit: "month",
            displayFormats: {
              month: "MMM",
            },
          },
          distribution: "linear",
          },
          {
            id: "bar",
          offset: true,
          type: "category",
          distribution: "series",
          }
      ],
      yAxes: [
        {
          ticks: {
            beginAtZero: true,
          },
        },
      ],
    },
  },
});

Leave a comment