Nicolas S.Xu
Nicolas S.Xu

Reputation: 14524

Chartjs bar order adjustment after bar chart is drawn

In the chartjs document, you can use update() method to redraw bar the value change, but not the bar label change, or bar order change.

What I want to do is to sort the bar order by label after new bar is added to chart by myBarChart.addData().

Here is my attempt to solve the problem which fails:

        this.myBarChart.addData([1], tickString);
        // TODO: need to sort here by tick string when adding new one!
        this.myBarChart.datasets[0].bars = _.sortBy(bars, function(bar){

            return parseFloat(bar.label); // label example: '1.223', '1.44'
        });

Question: If possible, how to sort bar by label for a chartjs chart after bar chart is drawn?

Upvotes: 1

Views: 4170

Answers (1)

potatopeelings
potatopeelings

Reputation: 41065

Here's how you do it with a separate function. Adapted from How can I sort, insert in between and update full dataset in chartjs?

var MyBarChartMethods = {
    // sort a dataset
    sortByLabel: function (chart) {
        // get data from chart elements (instead of messing up the actual data object)
        var data = []
        chart.datasets.forEach(function (dataset, i) {
            dataset.bars.forEach(function (bar, j) {
                if (i === 0) {
                    data.push({
                        label: parseFloat(chart.scale.xLabels[j]),
                        values: [bar.value]
                    })
                } else
                    data[j].values.push(bar.value)
            });
        })

        // sort the data based on label
        data.sort(function (a, b) {
            if (a.label > b.label)
                return 1;
            else if (a.label < b.label)
                return -1;
            else
                return 0;
        })

        // update the chart elements using the sorted data
        chart.datasets.forEach(function (dataset, i) {
            dataset.bars.forEach(function (bar, j) {
                if (i === 0)
                    chart.scale.xLabels[j] = data[j].label;
                bar.label = data[j].label;
                bar.value = data[j].values[i];
            })
        });
        chart.update();
    },
}

and you call it thus

MyBarChartMethods.sortByLabel(myBarChart)

Fiddle - http://jsfiddle.net/jk1k0g5u/

Upvotes: 1

Related Questions