Google Earth Engine Legend – Customizing a Continuous Legend in Google Earth Engine

color rampgoogle-earth-enginegoogle-earth-engine-javascript-apilegendraster

I've created legends in ggplot, which look like this

r ggplot legend

With the code I've used in Google Earth Engine, this is what my legend looks like

gee legend

Is there an easy way for me to edit my Google Earth Engine code to have it match what I've been making in ggplot? Code is as shown below.

 // Choose the yellow, orange, red colour palette with 9 classes
var palette = palettes.colorbrewer.YlOrRd[9];
var vis = {min: 0, max: 335, palette: palette};

// Create a mask to remove 0 values
merchantable = merchantable.updateMask(merchantable.neq(0));

// Add a raster layer and enable the colour palette
Map.addLayer(merchantable, {min: 0, max: 335, palette: palette});

// Creates a color bar thumbnail image for use in legend from the given color palette
function makeColorBarParams(palette) {
  return {
    bbox: [0, 0, 1, 0.1],
    dimensions: '100x10',
    format: 'png',
    min: 0,
    max: 1,
    palette: palette,
  };
}

// Create the colour bar for the legend
var colorBar = ui.Thumbnail({
  image: ee.Image.pixelLonLat().select(0),
  params: makeColorBarParams(vis.palette),
  style: {stretch: 'horizontal', margin: '0px 8px', maxHeight: '24px'},
});

// Create a panel with three numbers for the legend
var legendLabels = ui.Panel({
  widgets: [
    ui.Label(vis.min, {margin: '4px 8px'}),
    ui.Label(
        ((vis.max-vis.min) / 2+vis.min),
        {margin: '4px 8px', textAlign: 'center', stretch: 'horizontal'}),
    ui.Label(vis.max, {margin: '4px 8px'})
  ],
  layout: ui.Panel.Layout.flow('horizontal')
});

// Legend title
var legendTitle = ui.Label({
  value: 'Merchantable (tons C)',
  style: {fontWeight: 'bold'}
});

// Add the legendPanel to the map
var legendPanel = ui.Panel([legendTitle, colorBar, legendLabels]);
Map.add(legendPanel);

Best Answer

To make the color bar, you're using a pixelLatLon image, in the region of 0 to 1, with a min/max of 0/1, so you get a continuous spread of color (using 100 values from 0 to 1). To get discrete steps, use a larger range and truncate the numbers to integers. The following code produces 10 steps by using the region 0 to 10, with a max of 10.

var nSteps = 10
// Creates a color bar thumbnail image for use in legend from the given color palette
function makeColorBarParams(palette) {
  return {
    bbox: [0, 0, nSteps, 0.1],
    dimensions: '100x10',
    format: 'png',
    min: 0,
    max: nSteps,
    palette: palette,
  };
}

// Create the colour bar for the legend
var colorBar = ui.Thumbnail({
  image: ee.Image.pixelLonLat().select(0).int(),
  params: makeColorBarParams(vis.palette),
  style: {stretch: 'horizontal', margin: '0px 8px', maxHeight: '24px'},
});

https://code.earthengine.google.com/8c935da8a1f2a22f0c4b382e2267117b