Google Earth Engine – Creating Formatted Chart for Confusion Matrix

chart;confusion matrixgoogle-earth-engineremote sensingspatial statistics

I was curious how to create a formatted Confusion Matrix: (https://developers.google.com/earth-engine/apidocs/ee-confusionmatrix)

I've completed my Supervised Classification, and I've created a Confusion Matrix with these results:

List (4 elements)
0: [1145,1,4,222]
1: [0,645,0,0]
2: [7,11,219,549]
3: [0,0,0,0]

How do I create a polished, formatted chart in GEE?

Like this beauty, but additionally with my classification types listed (I'm using City, Water, Forest, and Other)

enter image description here

(Image from: https://manisha-sirsat.blogspot.com/2019/04/confusion-matrix.html )

var classNames = ['City', 'Water', 'Forest', 'Other']
var confusionMatrix = [
  [1145, 1, 4, 222],
  [0, 645, 0, 0],
  [7, 11, 219, 549],
  [0, 0, 0, 0]
]

var panel = ui.Panel([...]) // How do I create a table with formatting?
print(panel)

https://code.earthengine.google.com/4fd7b66c0d01ef87ce62990e8fe350d8

Best Answer

You can use the style argument when creating your ui widgets and use a subset of CSS to style them them. There are some missing features, like the border-collapse property, that makes it tricky to get pixel-perfect styling. Here's a starting point, which should point you in the right direction:

var classNames = ['City', 'Water', 'Forest', 'Other']
var confusionMatrix = [
  [1145, 1, 4, 222],
  [0, 645, 0, 0],
  [7, 11, 219, 549],
  [0, 0, 0, 0]
]

var styles = {
  topLabel: {
    width: '100%',
    textAlign: 'center',
    padding: '.5rem 1rem',
    fontWeight: 'bold',
    backgroundColor: '#FFEFF9',
    margin: '0',
    border: '1px solid black',
  },
  leftLabel: {
    width: '100%',
    textAlign: 'center',
    padding: '.5rem 1rem',
    fontWeight: 'bold',
    backgroundColor: '#FFEFF9',
    margin: '0',
    border: '1px solid black',
  },
  value: {
    width: '100%',
    padding: '.5rem .5rem',
    textAlign: 'right',
    margin: '0',
    border: '1px solid black',
  },
  blank: {
    width: '100%',
    padding: '.5rem',
    margin: '0',
    border: '1px solid rgba(0, 0, 0, 0)',
  }
}

function table(columns) {
  return ui.Panel(columns, ui.Panel.Layout.flow('horizontal'))
}

function column(widgets) {
  return ui.Panel(widgets, ui.Panel.Layout.flow('vertical'))
}

function cell(contents, styleName) {
  return ui.Label(contents, styles[styleName])
}

var labelColumn = column([cell(' ', 'blank')].concat(
  classNames.map(function (contents) {
    return cell(contents, 'leftLabel')
  })
))

var valueColumns = classNames.map(function (_, i) {
  return ui.Panel([cell(classNames[i], 'topLabel')].concat(
    classNames.map(function (_, j) {
      return cell(confusionMatrix[j][i], 'value')
    })
  ))
})

var panel = table(
  [labelColumn].concat(valueColumns)
)

print(panel)

https://code.earthengine.google.com/2cf1af6d384a6f5bb6982de3b4e8f6ec

Related Question