RubbelDieKatz
RubbelDieKatz

Reputation: 1187

Chart.js: Reverse bar chart with regular bars (Bottom to top instead of top to bottom)

I'm trying to create a bar chart for my user's grades. A grade 1 is very good, a grade 6 is very bad. I'd like the bar for grade 1 to be very tall and the bar for grade 6 to be very small. If I use the reverse option, this is not the case. Basically, I'd like the y-axis to be inversed, and the bars to rise from the bottom instead of the top.

Fiddle

var canvas = document.getElementById('myChart');
var data = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            label: "Grade",
            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: [1, 4, 6, 2, 3, 5, 6],
        }
    ]
};
var option = {
    scales: {
    yAxes:[{
            stacked:true,
        gridLines: {
            display:true,
          color:"rgba(255,99,132,0.2)"
        },
        ticks: {
           suggestedMin: 1,
           suggestedMax: 6,
           reverse: true
        }
    }],
    xAxes:[{
            gridLines: {
            display:false
        }
    }]
  }
};

var myBarChart = Chart.Bar(canvas,{
    data:data,
  options:option
});

Rough sketch of my desired result:

bar graph with bars from the bottom and inverted y axis

One option would be to colour the chart area in my desired colour, then change the bar colour to transparent and their width to 100%. That would at least make the bars slightly correct.


Note for people from the future: In addition to the accepted answer by @halliballi, I have added the following code to override the tooltips in the options section:

tooltips: {
        mode: 'index',
        intersect: false,
        callbacks: {
            title: function (tooltipItem, data)
            {
                return data['labels'][tooltipItem[0]['index']];
            },
            label: function (tooltipItem, data)
            {
                console.log(tooltipItem);
                return "Note: " +
                    (
                        7 - data['datasets'][0]['data'][tooltipItem['index']]
                    );
            }
        }
  },

Here's my finished graph:

graph of my finished result

Upvotes: 1

Views: 2618

Answers (1)

halliballi
halliballi

Reputation: 130

I think you could "invert" your values with 6 minus value for the value you want to display and then override the labels at y-axis

options: {
        scales: {
            yAxes: [{
                ticks: {
                    callback: function(value, index, values) {
                        return (6 - value);
                    }
                }
            }]
        }

Upvotes: 2

Related Questions