Chartjs 2: Multi level/hierarchical category axis in chartjs

Sebastien picture Sebastien · Oct 27, 2017 · Viewed 7.6k times · Source

Is it possible to define a bar chart with a multi level/category axis?

For instance I'd like to display the Region/Province categories like in this Excel chart: enter image description here

I found this example using multiple xAxes.

xAxes:[
    {
      id:'xAxis1',
      type:"category",
      ticks:{
        callback:function(label){
          var month = label.split(";")[0];
          var year = label.split(";")[1];
          return month;
        }
      }
    },
    {
      id:'xAxis2',
      type:"category",
      gridLines: {
        drawOnChartArea: false, // only want the grid lines for one axis to show up
      },
      ticks:{
        callback:function(label){
          var month = label.split(";")[0];
          var year = label.split(";")[1];
          if(month === "February"){
            return year;
          }else{
            return "";
          }
        }
      }
    }
  ]

The problem is it seems that the two axes are not really linked and the alignment of second axis is based on values instead of aligning in middle of lower level category. this case cause issues

Is there a clean way to achieve this in chart.js?

Update: I ended up creating a feature request on chartjs.

Answer

ishahadathb picture ishahadathb · Nov 12, 2017

you can provide value separately for different axis via datesets and provide an object with different configuration option (borderColor, pointBackgroundColor, pointBorderColor) etc, i hope It'll help.

here is the link for the with an update (fiddle you shared) Updated Fiddle

data: {
labels: ["January;2015", "February;2015", "March;2015", "January;2016", "February;2016", "March;2016"],
datasets: [{
  label: '# of Votes',
  xAxisID:'xAxis1',
  data: [12, 19, 3, 5, 2, 3]
},

// here i added another data sets for xAxisID 2 and it works just fine
{
  label: '# of Potatoes',
  xAxisID:'xAxis2',
  data: [9, 17, 28, 26, 29, 9]
}]

}

I hope that solves your problem :)