Horizontal Bar Configuration Chart.js

👍:0

If I have understood well, you would like to have a dataset, going to the right, and the other one to left.
If true, you should:

  1. set min:-100, max:100 and the ticks.callback, to return the absolute value of ticks in the x scale.
  2. add another x scale (i.e. x2) with min:-100, max:100 and reverse: true. Furthermore this scale shouldn’t be visible, therefore set also display: false.
  3. set xAxisID property in the second dataset to the new scale (x2).
const ctx = document.getElementById("myChart");
const myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['January', 'Fabruary', 'March', 'April', 'May', 'June', 'July'],
        datasets: [{
            label: 'user 1 online',
            data: [50, 35, 45, 47, 10, 3, 27],
            backgroundColor: 'rgba(40, 139, 170, 1)',
            borderWidth: 0,
            borderSkipped: false,
        },
        {
            label: 'user 2 online',
            data: [50, 35, 45, 47, 10, 3, 27],
            backgroundColor: 'orange',
            borderWidth: 0,
            borderSkipped: false,
            xAxisID: 'x2'
        }]
    },
    options: {
      indexAxis: 'y',
      scales: {
        x: {
          min: -100,
          max: 100,
          ticks: {
            callback(value) {
              return Math.abs(value);
            }
          }
        },
        x2: {
          display: false,
          min: -100,
          max: 100,
          reverse: true
        }
      }
    }
});
.myChartDiv {
  max-width: 600px;
  max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<html>
  <body>
    <div class="myChartDiv">
      <canvas id="myChart" width="600" height="400"/>
    </div>
  </body>
</html>

Leave a comment