Notification texts go here Contact Us Buy Now!

Chart.js stacked bar chart - sorting values in bar by value

var Sorted = {
        id: 'SortedStack',
        beforeDraw: function (chart, args, options) {
            if (options.enabled) {
                options.sortedData = [];

                for (var datasetIndex = 0; datasetIndex < chart.data.datasets.length; datasetIndex++) {
                    var dataset = chart.data.datasets[datasetIndex];


                    for (var index = 0; index < dataset.data.length; index++) {
                        var data = dataset.data[index];

                        if (!options.sortedData[index]) {
                            options.sortedData[index] = {
                                data: []
                            };
                        }

                        options.sortedData[index].data[datasetIndex] = {
                            datasetIndex: datasetIndex,
                            hidden: chart.getDatasetMeta(datasetIndex).hidden ? true : false,                            
                            value: dataset.data[index],
                            y: chart.getDatasetMeta(datasetIndex).data[index].y,
                            base: chart.getDatasetMeta(datasetIndex).data[index].base,
                        };

                    };
                };
                
                var chartTop = chart.scales.y.top;
                var max = chart.scales.y.max;
                var h = chart.scales.y.height / max;

                for (var datasetIndex = 0; datasetIndex < chart.data.datasets.length; datasetIndex++) {
                    var dataset = chart.data.datasets[datasetIndex];
                    

                    for (var index = 0; index < dataset.data.length; index++) {
                        var data = dataset.data[index];
                     
                        options.sortedData[index].data.sort(function (a, b) { return a.value - b.value; });
                        
                        for (var i = 0; i < options.sortedData[index].data.length; i++) {
                            var d = options.sortedData[index].data[i];
                
                            d.base = chartTop + (max - options.sortedData[index].data.reduce((a, b) => a + b.value, 0)) * h
                                + options.sortedData[index].data.filter(d => d.hidden).reduce((a, b) => a + b.value, 0) * h;
      
                            for (var j = 0; j < i; j++) {
                                d.base += options.sortedData[index].data[j].hidden
                                    ? 0
                                    : h * options.sortedData[index].data[j].value;
                            }

                            d.y = d.base + h * d.value;

                        };
                    }
                }
            }
        },
        beforeDatasetDraw: function (chart, args, options) {
            if (options.enabled) {
                chart.getDatasetMeta(args.index).data.forEach((data, index) => {
                    var el = options.sortedData[index].data.filter(e => e.datasetIndex === args.index)[0];
                    data.y = el.y;
                    data.base = el.base;
                });
            }
        }
    };
    
 var config =   {
  data: {
    labels: [
              "2018-07-06", "2018-07-07", "2018-07-08"       
    ],
    datasets: [
      {
        label: [
          "Dataset 1"
        ],
        data: [          1,2,3        ],
        backgroundColor: "red"
      },
      {
        label: [
          "Dataset 2"
        ],
        data: [          3,2,1        ],
        backgroundColor: "blue"
      },
      {
        label: [
          "Dataset 3"
        ],
        data: [          2,1,2        ],
        backgroundColor: "green"
      }
    ]
  },
  type: "bar",
  options: {
    responsive : true,
    maintainAspectRatio: false,
    plugins: {      
      SortedStack: {
        enabled: true
      }
    },    
    scales: {
      y: {
        axis: "y",
        type: "linear",
        Id: "y",
        stacked: true,
        position: "left",
        beginAtZero: true,
        ticks: {
          precision: 0
        }
      },
      x: {
        axis: "x",
        type: "category",
        Id: "x",
        stacked: true,
        position: "bottom",
        beginAtZero: false
      }
    },
    plugins: [Sorted]
  }
};

var chart = new Chart(document.getElementById('canvas'),config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>
<canvas id="canvas" height="500" width="500"></canvas>

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.