mikejohnson51 / climateR

An R 📦 for getting point and gridded climate data by AOI
https://mikejohnson51.github.io/climateR/
MIT License
170 stars 40 forks source link

Question and Help : A single Map for long term mean Raster (For Rainfall and Temperature) using terraclimate for a certain amount of years #58

Closed Heed725 closed 1 year ago

Heed725 commented 2 years ago

Hello Mike; Hopefully you got the email........My main issue was asking if there is specific code for displaying a single map of long term mean raster(Rainfall or Temperature) ......using Terraclimate and the other one was if if you have other Resources for Learning to use Terraclimate with R in order to display more maps.

Heed725 commented 2 years ago

Help

Rapsodia86 commented 2 years ago

If you want to calculate and plot mean value, you can use the same code that Mike has prepared for you #57 with just a slight modification for the mean calculation as below:

library(terra) library(rasterVis) library(AOI) library(climateR) library(RColorBrewer)

Get 6 years of tmax data for New York

AOI = aoi_get(state = "NY")

test_data <- getTerraClim( AOI = AOI, param = "tmax", startDate = "2014-01-01", endDate = "2019-12-31" )

We used 6 years, and want a annual max, so we need to apply "max" to every set of 12 layers

index = rep(1:6, each = 12)

annualMax = tapp(rast(test_data$terraclim_tmax), index = index, fun = "max") |> mask(vect(AOI))

We calculate mean velue using app() function from terra library and mask using AOI vector

long_mean = app(rast(test_data$terraclim_tmax), fun = "mean") |> mask(vect(AOI))

Plot

levelplot(annualMax, par.settings = rasterTheme(region = brewer.pal('YlOrRd', n = 9)), names.attr = as.character(c(2014:2019)))

image

Plot mean value

levelplot(long_mean, par.settings = rasterTheme(region = brewer.pal('YlOrRd', n = 9)), main= "Mean Tmax 2014-2019", margin=FALSE)

image

Heed725 commented 2 years ago

Brilliant the last part was what gave me hard part thank you 🙏..........if there like other resources for terraclimate in R I'll kindly need them🙏

Rapsodia86 commented 2 years ago

I think you are mixing a few things:

TerraClimate is a dataset of monthly climate and climatic water balance for global terrestrial surfaces from 1958-2019 (https://www.climatologylab.org/terraclimate.html) ClimateR is an R package that provides easy access to many climate resources: 1) some guidelines https://mikejohnson51.github.io/climateR-intro/#81 2) functions: https://rdrr.io/github/mikejohnson51/climateR/man/ 3) and obviously the Introduction with many examples on the main page: https://github.com/mikejohnson51/climateR

Terra (https://github.com/rspatial/terra) is an R package for spatial data analysis: https://rspatial.org/terra/spatial/index.html

Raster (https://github.com/rspatial/raster) is an R package for spatial data analysis that is being replaced by simpler and faster terra package.

RasterVis is an R package for data visualization (for terra and raster packages): https://oscarperpinan.github.io/rastervis/

So, you have to either look for packages and their functions descriptions to work with different climate datasets or for climate datasets descriptions themselves.

Heed725 commented 2 years ago

Thank you.

Heed725 commented 1 year ago

Hello again Doc @Rapsodia86 hopefully you're doing alright ....I have three questions..... QN 1: I know how to prepare yearly facets climate plot but when it comes to monthly its a difficult task for me like in the photo below any ideas or codes on how to reach there ...

Morogoro

Qn 2: Is on how to prepare a good land surface temperature Map(facets) using R ?

Qn 3: Is on how to prepare a good NDVI Map(facets) using R ?

Rapsodia86 commented 1 year ago

Could you share a code that you are struggling with?

Heed725 commented 1 year ago

library(terra) library(rasterVis) library(sf) library(climateR) library(RColorBrewer)

Get 6 years of tmax data for New York

KGZ <- st_read("c:/Morogoro.shp")

test_data <- getTerraClim( KGZ, param = "tmax", startDate = "2010-01-01", endDate = "2019-12-31"

index = rep(1:10, each = 12)

annualMax = tapp(rast(test_data$terraclim_tmax), index = index, fun = "max") |> mask(vect("c:/Morogoro.shp"))

Plot

levelplot(annualMax, par.settings = rasterTheme(region = brewer.pal('YlOrRd', n = 9)), names.attr = as.character(c(2010:2019)))

The part of index to turn it from Years to month basics there I don't know.....it's what I'm struggling there

Rapsodia86 commented 1 year ago

You have to change the indexing based on which you are calculating the mean.

library(terra)
library(rasterVis)
library(sf)
library(climateR)
library(RColorBrewer)
library(AOI)
AOI = aoi_get(state = "NY")

test_data <- getTerraClim(
  AOI=AOI,
  param = "tmax",
  startDate = "2010-01-01",
  endDate = "2019-12-31")

  index = rep(1:12, 10) #you need to change the indexing based on which you will be calculating your mean value; so now you have to repeat all months ten times

 #mean value
  monthlyMEANofMAX = tapp(rast(test_data$terraclim_tmax),
                   index = index,
                   fun = "mean") |>  mask(vect(AOI))

  ##Plot
  levelplot(monthlyMEANofMAX,
            par.settings = rasterTheme(region = brewer.pal('YlOrRd', n = 7)),
            names.attr = month.abb)

image

Heed725 commented 1 year ago

Thanks Doc hugely appreciate for that ........one last thing any tips in creating Land surface temperature and NDVI cool maps in R like same facets kinda way

Rapsodia86 commented 1 year ago

You can download MODIS 13A3 v061 1km products for monthly NDVI via e.g. https://appeears.earthdatacloud.nasa.gov/ . It allows you to crop & mask data for your area and download as tiff file. In terms of LST, there is 8-day product MODIS 11A2 v061 also available via AppEEARS. Then you can calculate mean values and plot them.

Heed725 commented 1 year ago

Huge huge thanks Doc 🙏

mikejohnson51 commented 1 year ago

@Rapsodia86 thank you for helping @Heed725 through this !!

Heed725 commented 1 year ago

Hello Doc, Hopefully you're doing well,I had a question on climateR..... there's been an update everything have been going well on this code except one part on masking

library(terra) library(rasterVis) library(sf) library(climateR) library(RColorBrewer) library(raster)

Get 6 years of tmax data for New York

KGZ <- st_read("c:/Dodoma.shp") plot(KGZ)

test_data <- getTerraClim( KGZ, varname = "ppt", startDate = "2010-01-01", endDate = "2019-12-31" ) index = rep(1:10, each = 12)

annualmax = app(rast(test_data$ppt), fun = "mean") |> mask(vect("c:/Dodoma.shp"))

Plot

levelplot(annualmax, par.settings = rasterTheme(region = brewer.pal('blues', n = 9)), names.attr = as.character(c(2010:2019)))

The annual max part is giving me error

Error: [mask] SpatRaster has no values

Is there a solution for that

Rapsodia86 commented 1 year ago

Works for me: and notice that it is called: test_data$ppt_total not _not testdata$ppt

library(terra)
library(rasterVis)
library(climateR)
library(RColorBrewer)
library(AOI)

AOI = aoi_get(state = "NY")

test_data <- getTerraClim(
  AOI=AOI,
  varname = "ppt",
  startDate = "2010-01-01",
  endDate = "2019-12-31")

AOI_proj <- project(vect(AOI),crs(test_data$ppt_total)) #needed to reproject the polygon. You may not need this.
#mean value
annualmean = app(test_data$ppt_total,fun = "mean") |> mask(AOI_proj)

##Plot
levelplot(annualmean,
          par.settings = rasterTheme(region = brewer.pal('Blues', n = 9)),
          main= "Mean PPT 2010-2019", margin=FALSE)

image

DorotheaDeus commented 1 year ago

Dear ALL,

I need your help, I am getting the following error; (I) I can not plot the downloaded raster object

plot(kilombero_2021.ppt) Error in xy.coords(x, y, xlabel, ylabel, log) : 'x' is a list, but does not have components 'x' and 'y'

ii) I Can not save using write Raster function

writeRaster(kilombero_2021.ppt,file.path=dir, filename = 'Kilombero_TerraClim_prcp_2021.tif', format='GTiff', bylayer=TRUE, overwrite=FALSE) Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘writeRaster’ for signature ‘"list", "character"’

My Code please assist...thanks in advance

downloading precipitation data for 1yrs

RASTER

Valid date ranges from 1958-01-01 to 2021-12-01

kilombero_2021.ppt=getTerraClim(Kilombero.sf, varname ='ppt',startDate = "2020-10-01",endDate = "2021-12-01")

show(kilombero_2021.ppt)

Display and Check

plot(kilombero_2021.ppt)

saving the raster files to my directory

dir<-"/Users/dorothy/Documents/MoW/Year4/Task_2_Capacity Building/Training_2_R_Data_Preparation_and_Management/Day2/Data"

writeRaster(kilombero_2021.ppt,file.path=dir, filename = 'Kilombero_TerraClim_prcp_2021.tif', format='GTiff', bylayer=TRUE, overwrite=FALSE)

mikejohnson51 commented 1 year ago

You'll need to atttach terra and be sure to access the list elements of the retuned object. Please try something like:

library(climateR); library(terra)

Kilombero.sf = AOI::aoi_get(state = "CO")

kilombero_2021.ppt=getTerraClim(Kilombero.sf, 
                                varname ='ppt',
                                startDate = "2020-10-01",
                                endDate = "2021-12-01")
#Display and Check
plot(kilombero_2021.ppt$ppt)

##saving the raster files to my directory
dir.create("data")
writeRaster(kilombero_2021.ppt$ppt,
            filename = 'data/Kilombero_TerraClim_prcp_2021.tif', 
            overwrite=FALSE)

rast('data/Kilombero_TerraClim_prcp_2021.tif')

unlink('data', recursive = TRUE)
Heed725 commented 1 year ago

Hello, Just Chipping in for Mike's solution I've also modified the code a bit (It works but this one might solve the case as this one read the actual Kilombero area ,Tanzania it can act as solution number 2)

library(terra) library(sf) library(climateR)

create a shapefile of Kilombero so as it can be read via st_read function

Kilombero.sf <- st_read("c:/Kilombero.shp") plot(Kilombero.sf)

kilombero_2021.ppt=getTerraClim(Kilombero.sf, varname ='ppt', startDate = "2020-10-01", endDate = "2021-12-01")

Display and Check

plot(kilombero_2021.ppt$ppt)

create a folder in local disk in this scenario its called data so as to save the raster downloaded

writeRaster(kilombero_2021.ppt$ppt, filename = 'c:/data/Kilombero_TerraClim_prcp_2021.tif', overwrite=FALSE)

rast('c:/data/Kilombero_TerraClim_prcp_2021.tif')

unlink('data', recursive = TRUE)

Kilombero