Google Earth Engine – Calculate Monthly Average NDVI and Format Date Correctly

google-earth-engine

I'm trying to create a chart that is a monthly average for each year from a 22-year MODIS NDVI image collection. I have a number of steps to complete. This is one of them. The closest answer I could find is from the solution in this post:

Google Earth Engine: calculating and plotting monthly average NDVI for a region from MODIS data

The code at the end of the above link uses xProperty: 'system:index' giving the x axis as numbers from 0 onwards. How can I use the year (y) and month (m to create a xProperty that is formatted as a date?

 //Define chart parameters
var chartParam = {
 title: 'Monthly average NDVI',
  hAxis: {title: 'Time'},
  vAxis: {title: 'Average NDVI'},
  };

//Plot the chart
var chart = ui.Chart.image.seriesByRegion({
  imageCollection: yrMo,
  regions: ukr,
  reducer: ee.Reducer.mean(),
  scale: 500,
   xProperty: 'system:index',
 seriesProperty: 'PROJECT'
    });
    //Print chart to console
    print(chart.setOptions(chartParam));

Best Answer

Instead of setting month and year in the mapped function, set a combined date parameter, and specify that as the x-axis:

var yrMo = ee.ImageCollection.fromImages(
  years.map(function (y) {
        return months.map(function (m) {
            return collection
              .filter(ee.Filter.calendarRange(y, y, 'year'))
              .filter(ee.Filter.calendarRange(m, m, 'month'))
              .mean()
              .set('date',ee.Date.fromYMD(y, m, 1).format("YYYY/MM"))

        });
    }).flatten());
...
//Plot the chart
var chart = ui.Chart.image.seriesByRegion({
  imageCollection: yrMo,
  regions: ukr,
  reducer: ee.Reducer.mean(),
  scale: 500,
  xProperty: 'date',
  seriesProperty: 'PROJECT'
});