[Chartjs]-Two xAxes horizontal bar chart Charts.js

6👍

ꜰɪʀꜱᴛ

set xAxisID: 'x2' for the second dataset, as such :

datasets: [{
      ...
   }, {
      label: "$Money",
      backgroundColor: "rgba(55,99,132,0.2)",
      borderColor: "rgba(255,99,132,1)",
      borderWidth: 1,
      hoverBackgroundColor: "rgba(55,99,132,0.4)",
      hoverBorderColor: "rgba(255,99,132,1)",
      data: [265, 459, 320, 181, 456, 555, 1040],
      xAxisID: 'x2',
   }]

ꜱᴇᴄᴏɴᴅ

set type: 'linear' and position: 'bottom' for the second x-axis, like so :

xAxes: [{
         ...
      }, {
         id: 'x2',
         type: 'linear',
         position: 'bottom',
         gridLines: {
            display: false
         }
      }]

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩

var canvas = document.getElementById('myChart');
var data = {
   labels: ["January", "February", "March", "April", "May", "June", "July"],
   datasets: [{
      label: "# Deals",
      backgroundColor: "rgba(255,99,132,0.2)",
      borderColor: "rgba(255,99,132,1)",
      borderWidth: 2,
      hoverBackgroundColor: "rgba(255,99,132,0.4)",
      hoverBorderColor: "rgba(255,99,132,1)",
      data: [15, 19, 5, 16, 1, 12, 8],
      xAxisID: 'x1',
   }, {
      label: "$Money",
      backgroundColor: "rgba(55,99,132,0.2)",
      borderColor: "rgba(255,99,132,1)",
      borderWidth: 1,
      hoverBackgroundColor: "rgba(55,99,132,0.4)",
      hoverBorderColor: "rgba(255,99,132,1)",
      data: [265, 459, 320, 181, 456, 555, 1040],
      xAxisID: 'x2',
   }]
};
var option = {
   scales: {
      yAxes: [{
         gridLines: {
            display: true,
            color: "rgba(255,99,132,0.2)"
         }
      }],
      xAxes: [{
         id: 'x1',
         gridLines: {
            display: false
         }
      }, {
         id: 'x2',
         type: 'linear',
         position: 'bottom',
         gridLines: {
            display: false
         }
      }]
   }
};
var ctx = document.getElementById("myChart").getContext('2d');

var myBarChart = new Chart(ctx, {
   type: 'horizontalBar',
   data: data,
   options: option
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.min.js"></script>
<canvas id="myChart" width="400" height="200"></canvas>

Leave a comment