Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add EE charting functions #1855

Open
wants to merge 17 commits into
base: master
Choose a base branch
from
Open

Add EE charting functions #1855

wants to merge 17 commits into from

Conversation

giswqs
Copy link
Member

@giswqs giswqs commented Dec 19, 2023

This PR adds more charting functions to the chart module.

Reference: https://developers.google.com/earth-engine/guides/charts_image

chart.image_byRegion

ecoregions = ee.FeatureCollection('projects/google/charts_feature_example')
normClim = ee.ImageCollection('OREGONSTATE/PRISM/Norm81m').toBands().select('[0-9][0-9]_tmean')
labels = list(calendar.month_abbr)[1:] # a list of month labels, e.g. ['Jan', 'Feb', ...]

chart.image_byRegion(
    image=normClim, 
    regions=ecoregions, 
    reducer="mean", 
    scale=500, 
    xProperty='label', 
    xlabel='Ecoregion',
    ylabel='Temperature',
    labels=labels,
    # colors=['red', 'green', 'blue'],
    )


@giswqs giswqs requested a review from jdbcode December 19, 2023 21:14
Copy link

github-actions bot commented Dec 19, 2023

@github-actions github-actions bot temporarily deployed to pull request December 19, 2023 21:21 Inactive
@giswqs
Copy link
Member Author

giswqs commented Dec 19, 2023

chart.image_byClass

Reference: https://developers.google.com/earth-engine/guides/charts_image#uichartimagebyclass

bqplot example with line smoothing

import numpy as np
import bqplot.pyplot as plt

fig = plt.figure(title="Random Walks")
x = np.arange(100)
# three random walks
y = np.random.randn(3, 100).cumsum(axis=1)

lines = plt.plot(
    x, y,
    labels=["Line1", "Line2", "Line 3"],
    display_legend=True
)

# Plot the lines with interpolation
line1 = plt.plot(x, y[0], 'b-', label='Line 1', interpolation='basis')
line2 = plt.plot(x, y[1], 'r-', label='Line 2', interpolation='step-after')
line3 = plt.plot(x, y[2], 'g-', label='Line 3', interpolation='cardinal')

plt.show()

@jdbcode
Copy link
Collaborator

jdbcode commented Dec 20, 2023

Hi @giswqs, just a quick note to say I see the review request and will follow up shortly.

@giswqs
Copy link
Member Author

giswqs commented Dec 20, 2023

No rush. I will be adding more commit over the next few days.

@github-actions github-actions bot temporarily deployed to pull request December 22, 2023 19:59 Inactive
@github-actions github-actions bot temporarily deployed to pull request December 22, 2023 21:25 Inactive
@github-actions github-actions bot temporarily deployed to pull request December 25, 2023 04:38 Inactive
@jdbcode
Copy link
Collaborator

jdbcode commented Jan 3, 2024

It looks like you're maybe still working on chart.image_byClass?
I saw the new Image_byClass class but the image_byClass function is unchanged from todo. Do you want to add it to this PR, or would you like to merge the current changes?

@giswqs
Copy link
Member Author

giswqs commented Jan 3, 2024

@jdbcode Thanks fort testing it. I will be adding more classes and functions. Don't merge this PR yet.

@jdbcode
Copy link
Collaborator

jdbcode commented Jan 3, 2024

Sounds good

@github-actions github-actions bot temporarily deployed to pull request January 3, 2024 21:55 Inactive
@smith-kyle
Copy link

I'm a little late to the party, but I noticed you all aren't using a notebook review tool and wanted to invite you to review this pull request with GitNotebooks: https://gitnotebooks.com/gee-community/geemap/pull/1855

It lets you do things like comment on rendered markdown and code cells, so might be an easy win for your PR reviews.

@github-actions github-actions bot temporarily deployed to pull request February 15, 2024 23:09 Inactive
@github-actions github-actions bot temporarily deployed to pull request May 25, 2024 12:29 Inactive
@giswqs giswqs changed the title Add image chart functions Add EE charting functions May 25, 2024
@github-actions github-actions bot temporarily deployed to pull request May 25, 2024 13:58 Inactive
@github-actions github-actions bot temporarily deployed to pull request May 25, 2024 23:55 Inactive
@giswqs
Copy link
Member Author

giswqs commented May 26, 2024

chart.image_byClass

Reference: https://developers.google.com/earth-engine/guides/charts_image#uichartimagebyclass

import ee
import geemap
from geemap.chart import BaseChart
import geemap.chart as chart
from bqplot import Figure, Lines, Axis, LinearScale, ColorScale
from IPython.display import display

geemap.ee_initialize()

ecoregions = ee.FeatureCollection('projects/google/charts_feature_example')

image = ee.ImageCollection('MODIS/061/MOD09A1') \
    .filter(ee.Filter.date('2018-06-01', '2018-09-01')) \
    .select('sur_refl_b0[0-7]') \
    .mean() \
    .select([2, 3, 0, 1, 4, 5, 6])

wavelengths = [469, 555, 655, 858, 1240, 1640, 2130]

fc = geemap.zonal_stats(
    image, ecoregions, stat_type="MEAN", scale=500, verbose=False, return_fc=True
)
bands = image.bandNames().getInfo()
df = geemap.ee_to_df(fc)[bands + ["label"]]

# Define the scales
x_sc = LinearScale()
y_sc = LinearScale()
color_sc = ColorScale()

lines = []
colors =  ['#f0af07', '#0f8755', '#76b349'] 

x_values = list(range(len(df.columns) - 1))
x_values = [469, 555, 655, 858, 1240, 1640, 2130]
band_names = ['B03', 'B04', 'B01', 'B02', 'B05', 'B06', 'B07']

for i, label in enumerate(df['label']):
    line = Lines(
        x=x_values, 
        y=df.iloc[i, :-1].values.astype(float),  # Ensure y-values are float
        scales={'x': x_sc, 'y': y_sc},
        colors=[colors[i]],
        labels=[label],
        display_legend=True,
        # interpolation='basis',
        stroke_width=3
    )
    lines.append(line)

x_ax = Axis(scale=x_sc, label='Wavelength (nm)', tick_values=x_values)
y_ax = Axis(scale=y_sc, orientation='vertical', label='Reflectance')

fig = Figure(marks=lines, axes=[x_ax, y_ax], title='Ecoregion Spectral Reflectance', legend_location='top-right')

display(fig)

no interpolation
image

basis interpolation
image

@giswqs
Copy link
Member Author

giswqs commented May 26, 2024

image_byClass

import ee
import geemap
import geemap.chart as chart

geemap.ee_initialize()

ecoregions = ee.FeatureCollection("projects/google/charts_feature_example")

image = (
    ee.ImageCollection("MODIS/061/MOD09A1")
    .filter(ee.Filter.date("2018-06-01", "2018-09-01"))
    .select("sur_refl_b0[0-7]")
    .mean()
    .select([2, 3, 0, 1, 4, 5, 6])
)

wavelengths = [469, 555, 655, 858, 1240, 1640, 2130]

fig = chart.image_byClass(
    image,
    classBand="label",
    region=ecoregions,
    reducer="MEAN",
    scale=500,
    xLabels=wavelengths,
    title="Ecoregion Spectral Signatures",
    x_label="Wavelength (nm)",
    y_label="Reflectance",
    interpolation="basis",
)
fig

image

@github-actions github-actions bot temporarily deployed to pull request May 26, 2024 04:50 Inactive
@giswqs
Copy link
Member Author

giswqs commented May 26, 2024

chart.image_histogram()
https://developers.google.com/earth-engine/guides/charts_image#uichartimagehistogram

import ee
import geemap.chart as chart
geemap.ee_initialize()

modis_sr = ee.ImageCollection('MODIS/061/MOD09A1') \
    .filter(ee.Filter.date('2018-06-01', '2018-09-01')) \
    .select(['sur_refl_b01', 'sur_refl_b02', 'sur_refl_b06']) \
    .mean()

hist_region = ee.Geometry.Rectangle([-112.60, 40.60, -111.18, 41.22])

hist_fig = chart.image_histogram(
    image=modis_sr, 
    region=hist_region, 
    scale=500, 
    maxBuckets=200, 
    minBucketWidth=1.0, 
    maxRaw=1000, 
    maxPixels=int(1e6),
    title='MODIS SR Reflectance Histogram',
    labels=['Red', 'NIR', 'SWIR'],
    colors=['#cf513e', '#1d6b99', '#f0af07']
)

hist_fig

image

@github-actions github-actions bot temporarily deployed to pull request May 26, 2024 13:28 Inactive
@github-actions github-actions bot temporarily deployed to pull request May 27, 2024 03:28 Inactive
@giswqs
Copy link
Member Author

giswqs commented May 27, 2024

Added chart.image_series() function
Reference: https://developers.google.com/earth-engine/guides/charts_image_collection#uichartimageseries

import ee
import geemap
import geemap.chart as chart

geemap.ee_initialize()

# Define the forest feature collection.
forest = ee.FeatureCollection("projects/google/charts_feature_example").filter(
    ee.Filter.eq("label", "Forest")
)

# Load MODIS vegetation indices data and subset a decade of images.
veg_indices = (
    ee.ImageCollection("MODIS/061/MOD13A1")
    .filter(ee.Filter.date("2010-01-01", "2020-01-01"))
    .select(["NDVI", "EVI"])
)

# Set the chart properties.
title = "Average Vegetation Index Value by Date for Forest"
xlabel = "Year"
ylabel = "Vegetation index (x1e4)"
colors = ["#e37d05", "#1d6b99"]
axes_options = {
    "x": {"label_offset": "30px"},
    "y": {"label_offset": "50px"},
}

# Create the chart.
fig = chart.image_series(
    veg_indices,
    region=forest,
    reducer=ee.Reducer.mean(),
    scale=500,
    xProperty="system:time_start",
    chart_type="LineChart",
    x_cols="date",
    y_cols=["NDVI", "EVI"],
    title=title,
    xlabel=xlabel,
    ylabel=ylabel,
    colors=colors,
    axes_options=axes_options,
)
fig

image

@github-actions github-actions bot temporarily deployed to pull request May 27, 2024 04:41 Inactive
@giswqs
Copy link
Member Author

giswqs commented May 27, 2024

Add chart.image_seriesByRegion() function.
Reference: https://developers.google.com/earth-engine/guides/charts_image_collection#uichartimageseriesbyregion

import ee
import geemap
import geemap.chart as chart

geemap.ee_initialize()

# Import the example feature collection.
ecoregions = ee.FeatureCollection('projects/google/charts_feature_example')

# Load MODIS vegetation indices data and subset a decade of images.
veg_indices = ee.ImageCollection('MODIS/061/MOD13A1') \
    .filter(ee.Filter.date('2010-01-01', '2020-01-01')) \
    .select(['NDVI'])

# Set the chart properties.
title = "Average NDVI Value by Date"
xlabel = "Date"
ylabel = "NDVI (x1e4)"
x_cols='index'
y_cols=["Desert", "Forest", "Grassland"]
colors = ['#f0af07', '#0f8755', '#76b349']
axes_options = {
    "x": {"label_offset": "30px"},
    "y": {"label_offset": "50px"},
}

# Create the chart.
fig = chart.image_seriesByRegion(
    veg_indices,
    regions=ecoregions,
    reducer=ee.Reducer.mean(),
    band="NDVI",
    scale=500,
    xProperty="system:time_start",
    seriesProperty="label",
    chart_type="LineChart",
    x_cols=x_cols,
    y_cols=y_cols,
    title=title,
    xlabel=xlabel,
    ylabel=ylabel,
    colors=colors,
    axes_options=axes_options,
    stroke_width=3,
    legend_location="bottom-left"
)
fig

image

@github-actions github-actions bot temporarily deployed to pull request May 27, 2024 05:39 Inactive
@github-actions github-actions bot temporarily deployed to pull request May 27, 2024 22:48 Inactive
@github-actions github-actions bot temporarily deployed to pull request June 3, 2024 01:17 Inactive
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants