Chartjs-Bi-directional horizontal bar chart using ng charts

2πŸ‘

βœ…

In the picture, the values on the left of the center are negative. Instead in your code are positive both datasets values. I assume you want to maintain the data but in the chart to see positive values in both directions.
If I have understood well, attached a sample.

const ctx = document.getElementById("myChart");
const myChart = new Chart(ctx, {
    type: 'horizontalBar',
    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: {
      scales: {
        yAxes: [{
          stacked: true,
          },
        ],
        xAxes: [{
          stacked: true,
          ticks: {
            callback(value) {
              return Math.abs(value);
            },
            min: -100,
            max: 100,
          }
        },
        {
          id: 'x2',
          type: 'linear',
          display: false,
          stacked: true,
          ticks: {
            min: -100,
            max: 100,
            reverse: true,
          }
        }]
      }
    }
});
.myChartDiv {
  max-width: 600px;
  max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4"></script>
<html>
  <body>
    <div class="myChartDiv">
      <canvas id="myChart" width="600" height="400"/>
    </div>
  </body>
</html>

0πŸ‘

You can use floating bars by specifying an array with 2 values instead of a single data point.

The 2 values are start and end so you can specify it as [0, actualValue]. Then you set the y axis to stacked and you will have that chart

Leave a comment