NDVI and NDWI from Google earth engine

Published

October 9, 2024

เปิดใช้ package ที่เกี่ยวข้อง

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.5
✔ forcats   1.0.0     ✔ stringr   1.5.1
✔ ggplot2   3.5.1     ✔ tibble    3.2.1
✔ lubridate 1.9.3     ✔ tidyr     1.3.1
✔ purrr     1.0.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(dismo)
Loading required package: raster
Loading required package: sp

Attaching package: 'raster'

The following object is masked from 'package:dplyr':

    select
library(geodata)
Loading required package: terra
terra 1.7.78

Attaching package: 'terra'

The following object is masked from 'package:tidyr':

    extract
library(tidyterra)

Attaching package: 'tidyterra'

The following object is masked from 'package:raster':

    select

The following object is masked from 'package:stats':

    filter
library(terra)

อ่านไฟล์โดยใช้คำสั่ง raster

NDVI<-raster("G:\\My Drive\\Gee data\\NDVI_from_S2_10m.tif", crs="EPSG:4326")

plot ไฟล์ที่นำเข้ามา

plot(NDVI)

ขอเปลี่ยนสีนิดนึง

custom_palette <- colorRampPalette(c("#2F527A", "#44916F"))

plot(NDVI, col = custom_palette(100))

น่าจะมีซัก 3 สีนะ

custom_palette <- colorRampPalette(c("#2F527A", "#FEDDB9","#44916F"))

plot(NDVI, col = custom_palette(100))

ลองใช้ ggplot

library(ggplot2)

ลอง plot ให้เหมือนอันก่อนหน้า

แต่ ggplot ต้องการ data ที่เป็น data frame

จึงต้องแปลง raster ให้เป็น data frame ก่อน

NDVI_df <- as.data.frame(NDVI, xy = TRUE)
colnames(NDVI_df)
[1] "x"  "y"  "B8"

ยาวหน่อย แต่ปรับอะไรได้หลากหลาย ใช้ ggplot

ggplot(data = NDVI_df, aes(x = x, y = y)) +
  geom_raster(aes(fill = B8)) +
  scale_fill_gradientn(colors = c("#2F527A", "#FEDDB9","#44916F")) +  # Custom color gradient
  coord_fixed() +
  theme_minimal() +
  labs(title = "NDVI by ggplot", x = "Longitude", y = "Latitude", fill = "NDVI value")

นำเข้าไฟล์ NDWI

NDWI<-raster("G:\\My Drive\\Gee data\\NDWI_from_S2_10m.tif", crs="EPSG:4326")

plot ไฟล์ NDWI

plot(NDWI)

check ดูว่ามีกี่ layers

nlayers(NDWI)
[1] 1

ลองปรับสี

custom_palette <- colorRampPalette(c("brown", "blue"))

plot(NDWI, col = custom_palette(100))

สีไม่สวย อยากได้แบบพลาสเทลๆ หน่อย

custom_palette <- colorRampPalette(c("#FEC89A", "#2F527A"))

plot(NDWI, col = custom_palette(100))

เตรียมข้อมูลเข้า ggplot

NDWI_df <- as.data.frame(NDWI, xy = TRUE)
colnames(NDWI_df)
[1] "x"  "y"  "B3"
ggplot(data = NDWI_df, aes(x = x, y = y)) +
  geom_raster(aes(fill = B3)) +
  scale_fill_gradientn(colors = c("#FEC89A", "#2F527A")) +  # Custom color gradient
  coord_fixed() +
  theme_minimal() +
  labs(title = "NDWI by ggplot", x = "Longitude", y = "Latitude", fill = "NDWI value")