Draw a horizontal bar chart from right to left

Issue

I am creating a horizontal bar chart in Chart.js as you can see in this jsfiddle.

I want to change the chart direction so that it draws from right to left. I tried dir = rtl and in CSS direction=rtl but they don’t work.

This is what I want:
expected chart output

Solution

I can’t find a native way in the documentation to do this, but you can do it via the fairly simple workaround of negating the data so that Chart.js draws negative values:

  1. invert the values in the dataset:

    data.datasets[0].data.map((currentValue, index, array) => {
      array[index] = currentValue * -1;
    });
    
  2. right-align the y-axis:

    scales: {
      yAxes: [{
        position: 'right'
        ...
    
  3. reformat tooltips for display:

    options = {
      tooltips: {
      callbacks: {
        label: function(tooltipItem, data) {
          var label = data.datasets[tooltipItem.datasetIndex].label || '';
    
          if (label) {
            label += ': ';
          }
          label += tooltipItem.xLabel * -1;
          return label;
        }
      }
      ...
    
  4. reformat ticks for display:

    xAxes: [{
      ticks: {
        callback: function(value, index, values) {
          return value * -1;
        }
    ...
    

Here’s a working example:

var data = {
  labels: ["x1", "x2", "x3", "x4", "x5"],
  datasets: [{
    label: "Actual",
    backgroundColor: 'rgba(0, 0, 255, 0.5)',
    borderWidth: 1,
    data: [40, 150, 50, 60, 70],
    yAxisID: "bar-y-axis1"
  }]
};

// invert the sign of each of the values.
data.datasets[0].data.map((currentValue, index, array) => {
  array[index] = currentValue * -1;
});

var options = {
  tooltips: {
    callbacks: {
      label: function(tooltipItem, data) {
        var label = data.datasets[tooltipItem.datasetIndex].label || '';

        if (label) {
          label += ': ';
        }
        label += tooltipItem.xLabel * -1; // invert the sign for display.
        return label;
      }
    }
  },
  scales: {
    yAxes: [{
      id: "bar-y-axis1",
      categoryPercentage: 0.5,
      barPercentage: 0.5,
      position: 'right' // right-align axis.
    }],

    xAxes: [{
      id: "bar-x-axis1",
      stacked: false,
      ticks: {
        callback: function(value, index, values) {
          return value * -1; // invert the sign for tick labelling.
        },
        beginAtZero: true
      }
    }]
  }
};

var ctx = document.getElementById("canvas").getContext("2d");
var myBarChart = new Chart(ctx, {
  type: 'horizontalBar',
  data: data,
  options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<canvas id="canvas"></canvas>

Answered By – timclutton

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published