Creating interactive chart in Jupyter Notebook using Geemap #1814
-
This code applied the custom date to the x-axis. But I do not want this. I want to show the date on which the Image is taken by using "system:index" property of the Image. Also, This code does not show the Interactive Chart, the NDVI Map, and the Shapefile together. This code shows the chart separately and shows the NDVI Map and Shapefile together. I want to show Chart, NDVI Map, and Shapefile together. import geopandas as gpd
import ee
import geemap
import os
import matplotlib.pyplot as plt
import datetime
# Initialize Earth Engine
ee.Initialize()
# Load the shapefile using GeoPandas
nReserve = gpd.read_file('D:/test/Chichawatni.shp')
# Create a GeoJSON representation from the GeoPandas dataframe
nReserve_geojson = geemap.gdf_to_ee(nReserve)
# Create a map for displaying the results
Map = geemap.Map()
# Calculate NDVI
def calculate_ndvi(image):
# Get the 'CLOUDY_PIXEL_PERCENTAGE' property of the image
cloudPercentage = ee.Number(image.get('CLOUDY_PIXEL_PERCENTAGE'))
# Calculate NDVI
ndviImage = image.expression(
'(NIR - RED) / (NIR + RED)',
{
'NIR': image.select('B8'),
'RED': image.select('B4'),
}
).float().rename('NDVI').copyProperties(image, ["system:time_start"])
# Add the 'CLOUDY_PIXEL_PERCENTAGE' property as an image property
return ndviImage.set('CLOUDY_PIXEL_PERCENTAGE', cloudPercentage)
start_date = '2023-07-15'
end_date = '2023-10-27'
# Define the Sentinel-2 collection
sentinel2_collection = ee.ImageCollection('COPERNICUS/S2_SR_HARMONIZED').filterDate(start_date, end_date)
# Filter the collection by date and AOI
filtered_collection = sentinel2_collection.filterBounds(nReserve_geojson).filterDate(start_date, end_date)
# Calculate NDVI for the filtered collection
ndvi_collection = filtered_collection.map(calculate_ndvi)
# Clip the NDVI to the shapefile
ndvi_clip = ndvi_collection.mean().clip(nReserve_geojson)
Map.centerObject(nReserve_geojson, 10) # Center the map on the shapefile
# Add the shapefile as an image layer
nReserve_image = ee.Image().paint(nReserve_geojson, 0, 2)
Map.addLayer(nReserve_image, {'palette': 'red'}, 'Shapefile')
# Add the NDVI layer on top
ndvi_viz_params = {
'min': -1,
'max': 1,
'palette': ['FFFFFF', 'CE7E45', 'DF923D', 'F1B555', 'FCD163', '99B718',
'74A901', '66A000', '529400', '3E8601', '207401', '056201',
'004C00', '023B01', '012E01', '011D01', '011301']
}
Map.addLayer(ndvi_clip, ndvi_viz_params, 'NDVI')
# Create a list of dates and 'CLOUDY_PIXEL_PERCENTAGE' values for the chart
def createChartData(image):
date = ee.Date(image.get('system:time_start'))
ndviValue = image.reduceRegion(
reducer=ee.Reducer.mean(),
geometry=nReserve_geojson,
scale=10,
maxPixels=1e13
).get('NDVI')
cloudPercentage = image.get('CLOUDY_PIXEL_PERCENTAGE')
return ee.Feature(None, {
'date': date,
'NDVI': ndviValue,
'Cloudy Percentage': cloudPercentage
})
chartData = ndvi_collection.map(createChartData)
# Extract dates and values from chartData
dates = chartData.aggregate_array('date').getInfo()
ndviValues = chartData.aggregate_array('NDVI').getInfo()
cloudPercentages = chartData.aggregate_array('Cloudy Percentage').getInfo()
# Convert dates to Python datetime objects
dates = [datetime.datetime.fromtimestamp(date['value'] / 1000) for date in dates]
# Create a line chart using Matplotlib
plt.figure(figsize=(10, 6))
# Plot NDVI values with label
ndvi_line, = plt.plot(dates, ndviValues, color='red')
plt.xlabel('Date')
plt.ylabel('NDVI')
# Create a secondary y-axis for Cloudy Percentage
ax2 = plt.twinx()
cloud_line, = ax2.plot(dates, cloudPercentages, color='blue')
ax2.set_ylabel('Cloud Percentage')
# Set custom date formatting for the x-axis
date_format = plt.matplotlib.dates.DateFormatter('%Y-%m-%d')
ax2.xaxis.set_major_formatter(date_format)
plt.gcf().autofmt_xdate()
# Customize the legend to include NDVI and Cloud Percentage
plt.legend([ndvi_line, cloud_line], ['NDVI', 'Cloud Percentage'])
# Display the chart
plt.show()
# Display the map with shapefile and NDVI layer
Map |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Get whatever data you need from Earth Engine, organize the data as a dataframe, then you can use your preferred library to plot the data. You can easily add plots to the map as a widget. See this example. https://github.com/gee-community/geemap/blob/master/examples/notebooks/geemap_matplotlib.ipynb |
Beta Was this translation helpful? Give feedback.
Get whatever data you need from Earth Engine, organize the data as a dataframe, then you can use your preferred library to plot the data. You can easily add plots to the map as a widget. See this example.
https://github.com/gee-community/geemap/blob/master/examples/notebooks/geemap_matplotlib.ipynb