I have a Google Chart that is created from a SharePoint List. The sorting of the chart results from which items appear first when going down from row to row:

function drawBarCharts(countChoices, name) {
        var rows = [];
        for (var property in countChoices) {
            if (countChoices.hasOwnProperty(property)) {
                rows.push([property, countChoices[property]]);
            }
        }


        var datatable = new google.visualization.DataTable();
        datatable.addColumn('string', 'Type');
        datatable.addColumn('number', 'Quantity');
        datatable.addRows(rows);
        var options = {
            title: String(name),
            is3D: 'true',
            hAxis:{direction: -1}
        };
        var chart = new google.visualization.BarChart(document.getElementById(String(name)));
        chart.draw(datatable, options);

How can I manually sort the data with a manual order, or by name?

Thanks!

up vote 1 down vote accepted

you can use a DataView and the setRows method to create a custom sort.
setRows takes an array of row indexes.

add the row indexes to the array in the order to be displayed,
then use the DataView to draw the chart.

see following code snippet...

google.charts.load('current', {
  packages:['corechart']
}).then(function () {
  var datatable = new google.visualization.DataTable();
  datatable.addColumn('string', 'Type');
  datatable.addColumn('number', 'Quantity');
  datatable.addRows([
    ['A', 2],
    ['B', 4],
    ['C', 6],
    ['S', 4],
    ['U', 2]
  ]);

  var dataview = new google.visualization.DataView(datatable);
  dataview.setRows([0, 2, 3, 4, 1]);

  var options = {
    title: 'Custom Sort',
    is3D: 'true',
    hAxis:{direction: -1}
  };

  var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
  chart.draw(dataview, options);
});

You can only sort by the columns that already added to the Datatable of the Google Chart desc or asc as the following

datatable.sort({column: 0, desc: true});

In this case, it will sort the datatable by Type column descending!

  • ok something was sorted, but not in the way i want it to be sorted. What are the options i have? – Fabian M Oct 12 at 8:26
  • As I told you it depends on the columns in your data table, so if you need to add order as you need , add a new column called order and set the order value like 1,2,3, and sort with this new column in your datatable !! – Mohamed El-Qassas MVP Oct 12 at 15:47

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.