Chartjs bar order adjustment after bar chart is drawn

房东的猫 提交于 2019-12-24 11:37:07

问题


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?


回答1:


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/



来源:https://stackoverflow.com/questions/31910960/chartjs-bar-order-adjustment-after-bar-chart-is-drawn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!