diff --git a/code/gee_charts/04-Advanced_Charts/02b_Box_Plots_(complete) b/code/gee_charts/04-Advanced_Charts/02b_Box_Plots_(complete) index d23268a4..f93be7ca 100644 --- a/code/gee_charts/04-Advanced_Charts/02b_Box_Plots_(complete) +++ b/code/gee_charts/04-Advanced_Charts/02b_Box_Plots_(complete) @@ -102,7 +102,7 @@ function formatDate(date) { .cat(month) .cat(', ') .cat(day) - .cat(ee.String(', 1)')); + .cat(ee.String(')')); } var rowList = dateList.map(function(date) { diff --git a/code/gee_charts/Supplement/DataTable_Colored_Bars b/code/gee_charts/Supplement/DataTable_Colored_Bars new file mode 100644 index 00000000..fd19c05f --- /dev/null +++ b/code/gee_charts/Supplement/DataTable_Colored_Bars @@ -0,0 +1,129 @@ +// Example script showing how to create a bar chart +// with each bar having a different color. + +// We create a map of forest loss with each pixel +// colored accoridng to the year in which the loss occurred. +// The chart displays the total loss in the region by year +// with the color or the bar matching the map. + +// Select a region +var geometry = ee.Geometry.Polygon([[ + [-66.31185532393005, -8.92550265818768], + [-66.31185532393005, -9.687127927480695], + [-65.2104759293988, -9.687127927480695], + [-65.2104759293988, -8.92550265818768] +]]); + +// Get the Hansen Global Forest Change dataset +// This dataset is updated yearly, so we get the latest version. +var gfc2022 = ee.Image('UMD/hansen/global_forest_change_2022_v1_10'); + +var lossYear = gfc2022.select(['lossyear']); + +// The lossYear image contains pixel values from 0 to 22 +// indicating the year in which the loss occurred + +// We visualize this layer on the map. +var palette = [ + '0083ba', '#4394b6', '#5ca5b2', '#74b6ad', '#8dc8a9', + '#a5d9a5', '#b7e2a8', '#c7e8ad', '#d7efb2', '#e7f5b7', + '#f7fcbc', '#fff7b6', '#fee8a4', '#fed890', '#fec980', + '#fdba6e', '#fba75e', '#f48b51', '#ed6e43', '#e5522a', + '#de3519', '#d7191c']; + +var lossYearVis = { + min: 0, + max: 22, + palette: palette +} +// Visualize the loss on the map +Map.centerObject(geometry, 10); +Map.setOptions('SATELLITE'); +Map.addLayer(geometry, {}, 'Selected Region', true, 0.6); +Map.addLayer(lossYear, lossYearVis, 'Loss Year'); + +// Create an area image and convert to Hectares +var areaImage = ee.Image.pixelArea().divide(1e5); + +// Add the band containing yearly loss +var areaImageWithYear = areaImage.addBands(lossYear); + +var areas = areaImageWithYear.reduceRegion({ + reducer: ee.Reducer.sum().group({ + groupField: 1, + groupName: 'year' + }), + geometry: geometry, + scale: 30, + maxPixels: 1e10 +}); + +var yearAreas = ee.List(areas.get('groups')); + +// Process results to extract the areas and +// create a list +var yearAreasList = ee.List(yearAreas.map(function(item) { + var areaDict = ee.Dictionary(item); + var yearString = ee.Number(areaDict.get('year')).format('20%02d'); + var area = ee.Number( + areaDict.get('sum')); + return ee.List([yearString, area]) +})); + +print('Year Areas', yearAreasList); + + +// We create a list of rows in the DataTable format +var rowList = yearAreasList.map(function(item) { + var year = ee.List(item).get(0); + var x = ee.String('Date(') + .cat(year) + .cat(', ') + .cat('0') + .cat(', ') + .cat('1') + .cat(ee.String(')')) + + var y = ee.List(item).get(1); + // We will assign the color to each year from the palette + var color = ee.List(palette).get(yearAreasList.indexOf(item)); + var rowDict = { + c: [{v: x}, {v: y}, {v: color}] + }; + return rowDict; +}); + +print('Rows', rowList); + +// Create the DataTable +rowList.evaluate(function(rowListClient) { + var dataTable = { + cols: [ + {id: 'x', type: 'date'}, + {id: 'y', label: 'area', type: 'number'}, + {id: 'style', label: 'Style', type: 'string', role: 'style'}, + + ], + rows: rowListClient + }; + + var options = { + title: 'Yearly Forest Loss', + vAxis: { + title: 'Area (Hectares)', + }, + hAxis: { + title: 'Year', + gridlines: {color: 'transparent'} + }, + legend: {position:'none'} + }; + + var chart = ui.Chart(dataTable, 'ColumnChart', options); + // Add the chart on the map + var chartPanel = ui.Panel({ + style: {width: '400px', position: 'middle-right'} + }); + chartPanel.add(chart); + Map.add(chartPanel); +}); diff --git a/code/gee_charts/Supplement/Night_Time_Lights_Trends b/code/gee_charts/Supplement/Night_Time_Lights_Trends index d418cd8a..1167284f 100644 --- a/code/gee_charts/Supplement/Night_Time_Lights_Trends +++ b/code/gee_charts/Supplement/Night_Time_Lights_Trends @@ -65,11 +65,11 @@ var createChart = function(cityName) { title: '', format: 'YYYY', ticks: [ - new Date(2013,1,1), - new Date(2015,1,1), - new Date(2017,1,1), - new Date(2019,1,1), - new Date(2021,1,1), + new Date(2013,0), // month indexing starts from 0 + new Date(2015,0), + new Date(2017,0), + new Date(2019,0), + new Date(2021,0), ], gridlines: {color: '#c7beb5'} }, diff --git a/code/gee_charts/Supplement/Transect_Chart b/code/gee_charts/Supplement/Transect_Chart new file mode 100644 index 00000000..7d9de5f9 --- /dev/null +++ b/code/gee_charts/Supplement/Transect_Chart @@ -0,0 +1,82 @@ +var transect = ee.Geometry.LineString([ + [139.0, 35.67], + [140.5, 35.67] +]); + +// Get VIIRS Annual NightTime Lights Image +var ntlCollection = ee.ImageCollection('NOAA/VIIRS/DNB/ANNUAL_V21'); +var band = 'average'; + +// Select a year +var year = 2021; +var startDate = ee.Date.fromYMD(year, 1, 1); +var endDate = startDate.advance(1, 'year'); +var image = ntlCollection + .filter(ee.Filter.date(startDate, endDate)) + .select(band) + .first(); +// Rename the band to 'DN' +var image = image.rename('DN'); +var resolution = image.projection().nominalScale(); +// Visualize the Image +var palette = ['000000', '584d9f','9c79c1','c98cbe','f2d192','e2ee82']; +var visParams = {min: 0.0, max: 80.0, palette: palette} +Map.addLayer(image, visParams, 'Night Lights ' + year); +Map.addLayer(transect, {color: 'red'}, 'transect'); + +// Generate Points along Line +var projection = 'EPSG:4326' // WGS84 +var interval = 0.01 // Degrees +var tolerance = 0.001; +var totalLength = transect.length({proj: projection, maxError: tolerance}); +var distances = ee.List.sequence(0, totalLength, interval); + +// Divide the line into segments of equal length +var parts = transect.cutLines({ + distances: distances, + proj: projection, + maxError: tolerance}); + +// The result is a MultiLine geometry +// Get the individual geometries and create a point +// from the start point of each line segment +var points = ee.FeatureCollection(parts.geometries().map(function(part) { + var startPoint = ee.Geometry(part).coordinates().get(0); + var point = ee.Algorithms.GeometryConstructors.Point(startPoint); + var coords = point.coordinates(); + return new ee.Feature(point, {'lat': coords.get(1), 'lon': coords.get(0)}); +})); + +Map.addLayer(points, {color: 'cyan'}, 'Points along transect'); + +// Extract the pixel values at each point +var samples = image.sampleRegions({ + collection: points, + properties: ['lat', 'lon'], + scale: resolution, +}); +print('Extracted Values', samples.first()); + +// Plot the results +var chart = ui.Chart.feature.byFeature({ + features: samples, + xProperty: 'lon', + yProperties: 'DN' +}).setChartType('AreaChart') + .setOptions({ + lineWidth: 1, + pointSize: 0, + title: 'Latitudinal Transect of Night Time Lights', + titleTextStyle: {fontSize: 18}, + vAxis: {title: 'DN', gridlines: {color: 'transparent'}}, + hAxis: {title: 'Longitude', gridlines: {color: 'transparent'}}, + series: { + 0: {color: 'blue'}, + }, + legend: {position: 'none'}, + curveType: 'function', + chartArea: {left: 100, right: 100}, + backgroundColor: 'transparent' + }) +print(chart); + \ No newline at end of file diff --git a/docs/code/gee_charts/04-Advanced_Charts/02b_Box_Plots_(complete) b/docs/code/gee_charts/04-Advanced_Charts/02b_Box_Plots_(complete) index d23268a4..f93be7ca 100644 --- a/docs/code/gee_charts/04-Advanced_Charts/02b_Box_Plots_(complete) +++ b/docs/code/gee_charts/04-Advanced_Charts/02b_Box_Plots_(complete) @@ -102,7 +102,7 @@ function formatDate(date) { .cat(month) .cat(', ') .cat(day) - .cat(ee.String(', 1)')); + .cat(ee.String(')')); } var rowList = dateList.map(function(date) { diff --git a/docs/code/gee_charts/Supplement/DataTable_Colored_Bars b/docs/code/gee_charts/Supplement/DataTable_Colored_Bars new file mode 100644 index 00000000..fd19c05f --- /dev/null +++ b/docs/code/gee_charts/Supplement/DataTable_Colored_Bars @@ -0,0 +1,129 @@ +// Example script showing how to create a bar chart +// with each bar having a different color. + +// We create a map of forest loss with each pixel +// colored accoridng to the year in which the loss occurred. +// The chart displays the total loss in the region by year +// with the color or the bar matching the map. + +// Select a region +var geometry = ee.Geometry.Polygon([[ + [-66.31185532393005, -8.92550265818768], + [-66.31185532393005, -9.687127927480695], + [-65.2104759293988, -9.687127927480695], + [-65.2104759293988, -8.92550265818768] +]]); + +// Get the Hansen Global Forest Change dataset +// This dataset is updated yearly, so we get the latest version. +var gfc2022 = ee.Image('UMD/hansen/global_forest_change_2022_v1_10'); + +var lossYear = gfc2022.select(['lossyear']); + +// The lossYear image contains pixel values from 0 to 22 +// indicating the year in which the loss occurred + +// We visualize this layer on the map. +var palette = [ + '0083ba', '#4394b6', '#5ca5b2', '#74b6ad', '#8dc8a9', + '#a5d9a5', '#b7e2a8', '#c7e8ad', '#d7efb2', '#e7f5b7', + '#f7fcbc', '#fff7b6', '#fee8a4', '#fed890', '#fec980', + '#fdba6e', '#fba75e', '#f48b51', '#ed6e43', '#e5522a', + '#de3519', '#d7191c']; + +var lossYearVis = { + min: 0, + max: 22, + palette: palette +} +// Visualize the loss on the map +Map.centerObject(geometry, 10); +Map.setOptions('SATELLITE'); +Map.addLayer(geometry, {}, 'Selected Region', true, 0.6); +Map.addLayer(lossYear, lossYearVis, 'Loss Year'); + +// Create an area image and convert to Hectares +var areaImage = ee.Image.pixelArea().divide(1e5); + +// Add the band containing yearly loss +var areaImageWithYear = areaImage.addBands(lossYear); + +var areas = areaImageWithYear.reduceRegion({ + reducer: ee.Reducer.sum().group({ + groupField: 1, + groupName: 'year' + }), + geometry: geometry, + scale: 30, + maxPixels: 1e10 +}); + +var yearAreas = ee.List(areas.get('groups')); + +// Process results to extract the areas and +// create a list +var yearAreasList = ee.List(yearAreas.map(function(item) { + var areaDict = ee.Dictionary(item); + var yearString = ee.Number(areaDict.get('year')).format('20%02d'); + var area = ee.Number( + areaDict.get('sum')); + return ee.List([yearString, area]) +})); + +print('Year Areas', yearAreasList); + + +// We create a list of rows in the DataTable format +var rowList = yearAreasList.map(function(item) { + var year = ee.List(item).get(0); + var x = ee.String('Date(') + .cat(year) + .cat(', ') + .cat('0') + .cat(', ') + .cat('1') + .cat(ee.String(')')) + + var y = ee.List(item).get(1); + // We will assign the color to each year from the palette + var color = ee.List(palette).get(yearAreasList.indexOf(item)); + var rowDict = { + c: [{v: x}, {v: y}, {v: color}] + }; + return rowDict; +}); + +print('Rows', rowList); + +// Create the DataTable +rowList.evaluate(function(rowListClient) { + var dataTable = { + cols: [ + {id: 'x', type: 'date'}, + {id: 'y', label: 'area', type: 'number'}, + {id: 'style', label: 'Style', type: 'string', role: 'style'}, + + ], + rows: rowListClient + }; + + var options = { + title: 'Yearly Forest Loss', + vAxis: { + title: 'Area (Hectares)', + }, + hAxis: { + title: 'Year', + gridlines: {color: 'transparent'} + }, + legend: {position:'none'} + }; + + var chart = ui.Chart(dataTable, 'ColumnChart', options); + // Add the chart on the map + var chartPanel = ui.Panel({ + style: {width: '400px', position: 'middle-right'} + }); + chartPanel.add(chart); + Map.add(chartPanel); +}); diff --git a/docs/code/gee_charts/Supplement/Night_Time_Lights_Trends b/docs/code/gee_charts/Supplement/Night_Time_Lights_Trends index d418cd8a..1167284f 100644 --- a/docs/code/gee_charts/Supplement/Night_Time_Lights_Trends +++ b/docs/code/gee_charts/Supplement/Night_Time_Lights_Trends @@ -65,11 +65,11 @@ var createChart = function(cityName) { title: '', format: 'YYYY', ticks: [ - new Date(2013,1,1), - new Date(2015,1,1), - new Date(2017,1,1), - new Date(2019,1,1), - new Date(2021,1,1), + new Date(2013,0), // month indexing starts from 0 + new Date(2015,0), + new Date(2017,0), + new Date(2019,0), + new Date(2021,0), ], gridlines: {color: '#c7beb5'} }, diff --git a/docs/code/gee_charts/Supplement/Transect_Chart b/docs/code/gee_charts/Supplement/Transect_Chart new file mode 100644 index 00000000..7d9de5f9 --- /dev/null +++ b/docs/code/gee_charts/Supplement/Transect_Chart @@ -0,0 +1,82 @@ +var transect = ee.Geometry.LineString([ + [139.0, 35.67], + [140.5, 35.67] +]); + +// Get VIIRS Annual NightTime Lights Image +var ntlCollection = ee.ImageCollection('NOAA/VIIRS/DNB/ANNUAL_V21'); +var band = 'average'; + +// Select a year +var year = 2021; +var startDate = ee.Date.fromYMD(year, 1, 1); +var endDate = startDate.advance(1, 'year'); +var image = ntlCollection + .filter(ee.Filter.date(startDate, endDate)) + .select(band) + .first(); +// Rename the band to 'DN' +var image = image.rename('DN'); +var resolution = image.projection().nominalScale(); +// Visualize the Image +var palette = ['000000', '584d9f','9c79c1','c98cbe','f2d192','e2ee82']; +var visParams = {min: 0.0, max: 80.0, palette: palette} +Map.addLayer(image, visParams, 'Night Lights ' + year); +Map.addLayer(transect, {color: 'red'}, 'transect'); + +// Generate Points along Line +var projection = 'EPSG:4326' // WGS84 +var interval = 0.01 // Degrees +var tolerance = 0.001; +var totalLength = transect.length({proj: projection, maxError: tolerance}); +var distances = ee.List.sequence(0, totalLength, interval); + +// Divide the line into segments of equal length +var parts = transect.cutLines({ + distances: distances, + proj: projection, + maxError: tolerance}); + +// The result is a MultiLine geometry +// Get the individual geometries and create a point +// from the start point of each line segment +var points = ee.FeatureCollection(parts.geometries().map(function(part) { + var startPoint = ee.Geometry(part).coordinates().get(0); + var point = ee.Algorithms.GeometryConstructors.Point(startPoint); + var coords = point.coordinates(); + return new ee.Feature(point, {'lat': coords.get(1), 'lon': coords.get(0)}); +})); + +Map.addLayer(points, {color: 'cyan'}, 'Points along transect'); + +// Extract the pixel values at each point +var samples = image.sampleRegions({ + collection: points, + properties: ['lat', 'lon'], + scale: resolution, +}); +print('Extracted Values', samples.first()); + +// Plot the results +var chart = ui.Chart.feature.byFeature({ + features: samples, + xProperty: 'lon', + yProperties: 'DN' +}).setChartType('AreaChart') + .setOptions({ + lineWidth: 1, + pointSize: 0, + title: 'Latitudinal Transect of Night Time Lights', + titleTextStyle: {fontSize: 18}, + vAxis: {title: 'DN', gridlines: {color: 'transparent'}}, + hAxis: {title: 'Longitude', gridlines: {color: 'transparent'}}, + series: { + 0: {color: 'blue'}, + }, + legend: {position: 'none'}, + curveType: 'function', + chartArea: {left: 100, right: 100}, + backgroundColor: 'transparent' + }) +print(chart); + \ No newline at end of file diff --git a/docs/gee-charts.html b/docs/gee-charts.html index 3aabb10a..6af98376 100644 --- a/docs/gee-charts.html +++ b/docs/gee-charts.html @@ -449,6 +449,10 @@

Ujaval Gandhi

id="toc-population-time-series">Population Time Series
  • Stacked Bar Chart
  • +
  • Colored Bar +Chart
  • +
  • Transect +Chart
  • References
  • Data Credits
  • @@ -1947,7 +1951,7 @@

    4.2 Box Plots

    .cat(month) .cat(', ') .cat(day) - .cat(ee.String(', 1)')); + .cat(ee.String(')')); } var rowList = dateList.map(function(date) { @@ -2255,11 +2259,11 @@

    Night Time Lights (NTL) Trends

    title: '', format: 'YYYY', ticks: [ - new Date(2013,1,1), - new Date(2015,1,1), - new Date(2017,1,1), - new Date(2019,1,1), - new Date(2021,1,1), + new Date(2013,0), // month indexing starts from 0 + new Date(2015,0), + new Date(2017,0), + new Date(2019,0), + new Date(2021,0), ], gridlines: {color: '#c7beb5'} }, @@ -2457,6 +2461,242 @@

    Stacked Bar Chart

    // Print the chart print(chart); +
    +

    Colored Bar Chart

    +

    It is possible to assign a different color to each bar of a bar +chart. You neeed to create a DataTable with a column having a +style role and define the color for each row. Here we create a +chart that uses a unique color for each bar that representing the year +of forest loss. The chart has a one-to-one correspondence with the map +palette - making it a very useful tool in interpretation of the spatial +and temporal aspects of the trend.

    +
    +Colored BarChart +

    +Colored BarChart +

    +
    +
    // Example script showing how to create a bar chart
    +// with each bar having a different color.
    +
    +// We create a map of forest loss with each pixel 
    +// colored accoridng to the year in which the loss occurred.
    +// The chart displays the total loss in the region by year
    +// with the color or the bar matching the map.
    +
    +// Select a region
    +var geometry = ee.Geometry.Polygon([[
    +  [-66.31185532393005, -8.92550265818768],
    +  [-66.31185532393005, -9.687127927480695],
    +  [-65.2104759293988, -9.687127927480695],
    +  [-65.2104759293988, -8.92550265818768]
    +]]);
    +
    +// Get the Hansen Global Forest Change dataset
    +// This dataset is updated yearly, so we get the latest version.
    +var gfc2022 = ee.Image('UMD/hansen/global_forest_change_2022_v1_10');
    +
    +var lossYear = gfc2022.select(['lossyear']);
    +
    +// The lossYear image contains pixel values from 0 to 22
    +// indicating the year in which the loss occurred
    +
    +// We visualize this layer on the map.
    +var palette = [
    +  '0083ba', '#4394b6', '#5ca5b2', '#74b6ad', '#8dc8a9',
    +  '#a5d9a5', '#b7e2a8', '#c7e8ad', '#d7efb2', '#e7f5b7',
    +  '#f7fcbc', '#fff7b6', '#fee8a4', '#fed890', '#fec980',
    +  '#fdba6e', '#fba75e', '#f48b51', '#ed6e43', '#e5522a',
    +  '#de3519', '#d7191c'];
    +
    +var lossYearVis = {
    +  min: 0,
    +  max: 22,
    +  palette: palette
    +}
    +// Visualize the loss on the map
    +Map.centerObject(geometry, 10);
    +Map.setOptions('SATELLITE');
    +Map.addLayer(geometry, {}, 'Selected Region', true, 0.6);
    +Map.addLayer(lossYear, lossYearVis, 'Loss Year');
    +
    +// Create an area image and convert to Hectares
    +var areaImage = ee.Image.pixelArea().divide(1e5);
    +
    +// Add the band containing yearly loss
    +var areaImageWithYear = areaImage.addBands(lossYear);
    +
    +var areas = areaImageWithYear.reduceRegion({
    +  reducer: ee.Reducer.sum().group({
    +    groupField: 1,
    +    groupName: 'year'
    +    }),
    +  geometry: geometry,
    +  scale: 30,
    +  maxPixels: 1e10
    +});
    +
    +var yearAreas = ee.List(areas.get('groups'));
    +
    +// Process results to extract the areas and
    +// create a list
    +var yearAreasList = ee.List(yearAreas.map(function(item) {
    +  var areaDict = ee.Dictionary(item);
    +  var yearString = ee.Number(areaDict.get('year')).format('20%02d');
    +  var area = ee.Number(
    +    areaDict.get('sum'));
    +  return ee.List([yearString, area])
    +}));
    +
    +print('Year Areas', yearAreasList);
    +
    +
    +// We create a list of rows in the DataTable format
    +var rowList = yearAreasList.map(function(item) {
    +  var year = ee.List(item).get(0);
    +  var x = ee.String('Date(')
    +    .cat(year)
    +    .cat(', ')
    +    .cat('0')
    +    .cat(', ')
    +    .cat('1')
    +    .cat(ee.String(')'))
    +    
    +  var y = ee.List(item).get(1);
    +  // We will assign the color to each year from the palette
    +  var color = ee.List(palette).get(yearAreasList.indexOf(item));
    +  var rowDict = {
    +    c: [{v: x}, {v: y}, {v: color}]
    +  };
    +  return rowDict;
    +});
    +
    +print('Rows', rowList);
    +
    +// Create the DataTable
    +rowList.evaluate(function(rowListClient) {
    +  var dataTable = {
    +    cols: [
    +      {id: 'x', type: 'date'},
    +      {id: 'y', label: 'area', type: 'number'},
    +      {id: 'style', label: 'Style', type: 'string', role: 'style'},
    +
    +    ],
    +    rows: rowListClient
    +  };
    +  
    +  var options = {
    +    title: 'Yearly Forest Loss',
    +    vAxis: {
    +      title: 'Area (Hectares)', 
    +    },
    +    hAxis: {
    +      title: 'Year',
    +      gridlines: {color: 'transparent'}
    +    },
    +    legend: {position:'none'}
    +  };
    +  
    +  var chart = ui.Chart(dataTable, 'ColumnChart', options);
    +  // Add the chart on the map
    +  var chartPanel = ui.Panel({
    +    style: {width: '400px', position: 'middle-right'}
    +  });
    +  chartPanel.add(chart);
    +  Map.add(chartPanel);
    +});
    +
    +
    +

    Transect Chart

    +

    You can sample values from an image along a line transect and +generate a FeatureCollection with latitude, longitude and DN values. +This can be then plotted to create a transect chart like below.

    +

    +
    var transect = ee.Geometry.LineString([
    +  [139.0, 35.67],
    +  [140.5, 35.67]
    +]);
    +
    +// Get VIIRS Annual NightTime Lights Image
    +var ntlCollection = ee.ImageCollection('NOAA/VIIRS/DNB/ANNUAL_V21');
    +var band = 'average';
    +
    +// Select a year
    +var year = 2021;
    +var startDate = ee.Date.fromYMD(year, 1, 1);
    +var endDate = startDate.advance(1, 'year');
    +var image = ntlCollection
    +  .filter(ee.Filter.date(startDate, endDate))
    +  .select(band)
    +  .first();
    +// Rename the band to 'DN'
    +var image = image.rename('DN');
    +var resolution = image.projection().nominalScale();
    +// Visualize the Image
    +var palette =  ['000000', '584d9f','9c79c1','c98cbe','f2d192','e2ee82'];
    +var visParams = {min: 0.0, max: 80.0, palette: palette}
    +Map.addLayer(image, visParams, 'Night Lights ' + year);
    +Map.addLayer(transect, {color: 'red'}, 'transect');
    +
    +// Generate Points along Line
    +var projection = 'EPSG:4326' // WGS84
    +var interval = 0.01 // Degrees
    +var tolerance = 0.001;
    +var totalLength = transect.length({proj: projection, maxError: tolerance});
    +var distances = ee.List.sequence(0, totalLength, interval);
    +
    +// Divide the line into segments of equal length
    +var parts = transect.cutLines({
    +  distances: distances,
    +  proj: projection,
    +  maxError: tolerance});
    +
    +// The result is a MultiLine geometry
    +// Get the individual geometries and create a point
    +// from the start point of each line segment
    +var points = ee.FeatureCollection(parts.geometries().map(function(part) {
    +  var startPoint = ee.Geometry(part).coordinates().get(0);
    +  var point = ee.Algorithms.GeometryConstructors.Point(startPoint);
    +  var coords = point.coordinates(); 
    +  return new ee.Feature(point, {'lat': coords.get(1), 'lon': coords.get(0)});
    +}));
    +
    +Map.addLayer(points, {color: 'cyan'}, 'Points along transect');
    +
    +// Extract the pixel values at each point
    +var samples = image.sampleRegions({
    +  collection: points,
    +  properties: ['lat', 'lon'],
    +  scale: resolution,
    +});
    +print('Extracted Values', samples.first());
    +
    +// Plot the results
    +var chart = ui.Chart.feature.byFeature({
    +  features: samples,
    +  xProperty: 'lon',
    +  yProperties: 'DN'
    +}).setChartType('AreaChart')
    +  .setOptions({
    +    lineWidth: 1,
    +    pointSize: 0,
    +    title: 'Latitudinal Transect of Night Time Lights',
    +    titleTextStyle: {fontSize: 18},
    +    vAxis: {title: 'DN', gridlines: {color: 'transparent'}},
    +    hAxis: {title: 'Longitude', gridlines: {color: 'transparent'}},
    +    series: {
    +      0: {color: 'blue'},
    +    },
    +    legend: {position: 'none'},
    +    curveType: 'function',
    +    chartArea: {left: 100, right: 100},
    +    backgroundColor: 'transparent'
    +  })
    +print(chart);
    +  
    +

    References

    diff --git a/docs/images/gee_charts/colored_barchart.png b/docs/images/gee_charts/colored_barchart.png new file mode 100644 index 00000000..29476f86 Binary files /dev/null and b/docs/images/gee_charts/colored_barchart.png differ diff --git a/docs/images/gee_charts/transect.png b/docs/images/gee_charts/transect.png new file mode 100644 index 00000000..c7f5c545 Binary files /dev/null and b/docs/images/gee_charts/transect.png differ diff --git a/gee-charts.Rmd b/gee-charts.Rmd index cc190af9..699e2add 100644 --- a/gee-charts.Rmd +++ b/gee-charts.Rmd @@ -555,6 +555,27 @@ knitr::include_graphics('images/gee_charts/stacked.png') ```{js eval=FALSE, code=readLines('code/gee_charts/Supplement/Stacked_BarChart')} ``` +## Colored Bar Chart + +It is possible to assign a different color to each bar of a bar chart. You neeed to create a DataTable with a column having a *style* role and define the color for each row. Here we create a chart that uses a unique color for each bar that representing the year of forest loss. The chart has a one-to-one correspondence with the map palette - making it a very useful tool in interpretation of the spatial and temporal aspects of the trend. + +```{r echo=FALSE, fig.align='center', out.width='75%', fig.cap='Colored BarChart'} +knitr::include_graphics('images/gee_charts/colored_barchart.png') +``` + +```{js eval=FALSE, code=readLines('code/gee_charts/Supplement/DataTable_Colored_Bars')} +``` + +## Transect Chart + +You can sample values from an image along a line transect and generate a FeatureCollection with latitude, longitude and DN values. This can be then plotted to create a transect chart like below. + +```{r echo=FALSE, fig.align='center', out.width='75%'} +knitr::include_graphics('images/gee_charts/transect.png') +``` + +```{js eval=FALSE, code=readLines('code/gee_charts/Supplement/Transect_Chart')} +``` # References diff --git a/images/gee_charts/colored_barchart.png b/images/gee_charts/colored_barchart.png new file mode 100644 index 00000000..29476f86 Binary files /dev/null and b/images/gee_charts/colored_barchart.png differ diff --git a/images/gee_charts/transect.png b/images/gee_charts/transect.png new file mode 100644 index 00000000..c7f5c545 Binary files /dev/null and b/images/gee_charts/transect.png differ