clip raster by raster

เปิดใช้งาน 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)
library(sf)
Linking to GEOS 3.12.1, GDAL 3.8.4, PROJ 9.3.1; sf_use_s2() is TRUE

นำเข้าไฟล์ที่มีขอบเขตใหญ่เกินความต้องการ

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

นำเข้าไฟล์ที่มีขอบเขตตรงตามความต้องการ

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

การตัดส่วนที่ไม่ต้องการออก ต้องใช้ 2 คำสั่งต่อเนื่องกัน

1. คำสั่งแรกคือ crop โดย output ที่ได้จะเป็น กรอบสี่เหลี่ยมของชุดมูล

bio01_reg<-crop(bio01_roi, bio12_Thai)
plot(bio01_reg)

2. คำสั่งแรกคือ mask คือการสั่งให้แสดงเฉพาะข้อมูลที่อยู่ในขอบเขตที่ต้องการ

bio01_Thai<-mask(bio01_reg, bio12_Thai)
plot(bio01_Thai)

ปรับการแสดงสีให้เข้ากับชุดข้อมูล

bio01_Thai_df <- as.data.frame(bio01_Thai, xy = TRUE)

ggplot(data = bio01_Thai_df, aes(x = x, y = y)) +
  geom_raster(aes(fill = bio01)) +
  scale_fill_gradientn(colors = c("#80BCBD", "#D4E7C5", "#DA8359")) +  # Custom color gradient
  coord_fixed() +
  theme_minimal() +
  labs(title = "Annual mean temperature", x = "Longitude", y = "Latitude", fill = "Temperature (c*10)")

เปลี่ยนหน่วยจาก c*10 ให้เป็น c ธรรมดา

1. เขียนการแปลงหน่วย

bio01_Thai_df$bio01c<-bio01_Thai_df$bio01/10

2. สร้างกราฟจากข้อมูลที่แปลงหน่วยได้

ggplot(data = bio01_Thai_df, aes(x = x, y = y)) +
  geom_raster(aes(fill = bio01c)) +
  scale_fill_gradientn(colors = c("#80BCBD", "#D4E7C5", "#DA8359")) +  # Custom color gradient
  coord_fixed() +
  theme_minimal() +
  labs(title = "Annual mean temperature", x = "Longitude", y = "Latitude", fill = "Temperature (c)")