TransWikia.com

Sort column by values in ui.Chart.feature.byProperty in Google Earth Engine

Geographic Information Systems Asked on July 25, 2021

I am creating a bar chart of band importance of a random forest classifier in GEE. The default bar order seems to be by name. How can I sort the columns in descending order depending on each column value?

This is the code I am using to create the chart:

// classifier information
var exp = classifier.explain();
print('RF explained', exp);


var band_importance = ee.Feature(null, ee.Dictionary(exp).get('importance'));

var chart =
ui.Chart.feature.byProperty(band_importance)
.setChartType('ColumnChart')
.setOptions({
title: 'Random forest band importance',
legend: {position: 'none'},
hAxis: {title: 'Bands'},
vAxis: {title: 'Importance'}
});
 
print(chart);

This is the resulting chart:
chart:

This is the link to the code: example

One Answer

Dictionaries (and Feature properties) aren't ordered, so you have to jump through some hoops to convert them into something that has an order first.

Get the importance keys and values as lists, sort them, convert to a Chart API DataTable and plot that: https://code.earthengine.google.com/4ae6b783c20dc09aed826a358b94552f

var importance = ee.Dictionary(exp.get('importance'))
var keys = importance.keys().sort(importance.values()).reverse()
var values = importance.values(keys);
var rows = keys.zip(values).map(function(list) {
  return {c: ee.List(list).map(function(n) { return {v: n}; })}
})

var dataTable = {
  cols: [{id: 'band', label: 'Band', type: 'string'},
         {id: 'importance', label: 'Importance', type: 'number'}],
  rows: rows.getInfo()
};

Correct answer by Noel Gorelick on July 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP