r sp/maps/maptools libraries: Map of annual solar irradiation in R - r

I am trying to plot annual solar irradiation data with different color on a world map. I am using R programming for the purpose.
The data I am using is from http://eosweb.larc.nasa.gov/sse/global/text/global_radiation
First, I am converting this data to a spatial dataframe and also the world map that is obtained using map(world) function to a spatial form.
I am following an example for practice from https://www.r-bloggers.com/maps-of-solar-radiation/
for plotting my code is as follows. I believe the code is completely correct but I am getting some errors
library(sp)
library(maps)
library(mapdata)
library(maptools)
library(RColorBrewer)
nasafile <- 'http://eosweb.larc.nasa.gov/sse/global/text/global_radiation'
nasa <- read.table(file=nasafile, skip=13, header=TRUE)
proj <- CRS('+proj=latlon +ellps=WGS84')
coords = nasa[,2:1]
datos = nasa[,3:15]
nasaSP <- SpatialPixelsDataFrame(points=coords, data=datos, proj4string=proj)
world <- map("world", plot=FALSE)
llCRS <- CRS("+proj=latlong +ellps=WGS84")
world_sp <- map2SpatialLines(world, proj4string=llCRS)
colar_sp = colorRampPalette(c("snow1", "thistle1", "plum2", "red4"))
map_sp <- list('sp.lines', world_sp)
spplot(nasaSP["Ann"], col.regions=color_sp, sp.layout=map_sp)
The main errors I'm getting are related to projections. I believe the way I have added them in code is correct and have seen many examples in which they have been written the same way. Please have a look at these errors and lemme know how can I make this code work.
Thanks in Advance!
Errors:
Error in CRS("+proj=latlon +ellps=WGS84") :
northings must follow eastings: +proj=latlon +ellps=WGS84
Error in checkSlotAssignment(object, name, value) :
assignment of an object of class “function” is not valid for slot ‘proj4string’ in an object of class “Spatial”; is(value, "CRS") is not TRUE
Error in CRS("+proj=latlong +ellps=WGS84") :
northings must follow eastings: +proj=latlong +ellps=WGS84
Error in initialize(value, ...) : object 'llCRS' not found

I found two problems with your code:
1) you're using CRS wrongly. In CRS("+proj=latlong...) instead of latlong you must use longlat (see ?CRS);
2) When you plot your map, your color_sp is called colar_sp.
Here is your code with the corrections:
library(sp)
library(maps)
library(mapdata)
library(maptools)
library(RColorBrewer)
nasafile <- 'http://eosweb.larc.nasa.gov/sse/global/text/global_radiation'
nasa <- read.table(file=nasafile, skip=13, header=TRUE)
proj <- CRS("+proj=longlat + datum=WGS84")
coords = nasa[,2:1]
datos = nasa[,3:15]
nasaSP <- SpatialPixelsDataFrame(points=coords, data=datos, proj4string=proj)
world <- map("world", plot=FALSE)
llCRS <- CRS("+proj=longlat + datum=WGS84")
world_sp <- map2SpatialLines(world, proj4string=llCRS)
color_sp = colorRampPalette(c("snow1", "thistle1", "plum2", "red4"))
map_sp <- list('sp.lines', world_sp)
spplot(nasaSP["Ann"], col.regions=color_sp, sp.layout=map_sp)

Related

adehabitatHR: In proj4string(xy) : CRS object has comment, which is lost in output

I'm trying to create kernel density map from point data (available as .shp and .csv) for 5 different species,at global scale. For some individual, there is only one point locality, but for the others there are few to several points. I will use the output map of KDE to identify the hotspots. I'm using adehabitatHR to produce KDE map as below:
library("sp")
library("rgdal")
library("rgeos")
# load the data layer
data.Points <- readOGR("D:/FGH/merged","data")
#Defining a CRS with sp cause coordinate reference systems are represented differently when PROJ < 6 and PROJ >= 6.
crs_wgs84 <- CRS(SRS_string = "EPSG:4326") # WGS 84 has EPSG code 4326
class(crs_wgs84)
wkt_wgs84 <- wkt(crs_wgs84)
cat(wkt_wgs84)
#Set the CRS of a Spatial* object in sp
data.Points2 <- data.Points
coordinates(data.Points2) <- ~ x + y
slot(data.Points2, "proj4string") <- crs_wgs84
library(raster)
library(adehabitatHR)
# Define the Domain
x <- seq(-179.8300, 179.2461, by=0.083333333) # resolution is the pixel size you desire
y <- seq(-42, 52, by=0.083333333)
xy <- expand.grid(x=x,y=y)
coordinates(xy) <- ~x+y
gridded(xy) <- TRUE
class(xy)
# runs the kernel density estimation
kde.output <- kernelUD(data.Points2, h="href", grid = xy)
However, I got this error when either using .shp or .csv input file:
In proj4string(xy) : CRS object has comment, which is lost in output
I went through https://cran.r-project.org/web/packages/sp/vignettes/CRS_warnings.html and https://inbo.github.io/tutorials/tutorials/spatial_crs_coding/, and did some modifies as above but the warning message is remained!
So, how can I get rid of this warning message? Is there any wrong command used?
Thanks for your help.

How can I clip a shapefile to my raster using R?

I am trying to mask a raster to a shapefile boundary, but I am getting an error. How can I correctly perform this mask?
The raw data can be found here, entitled "data_for_question.txt." It is formatted so that users can copy and paste (from the web app) the text directly into an R window and generate a data frame. Otherwise, if one doesn't want to generate the data, the output raster (example_raster.tif) and shapefile (field_boundary.shp) can both also be found in the same link.
Here is what I have tried:
#Import necessary libraries
library(pacman)
p_load(sf,
spatstat,
maptools,
tidyverse,
ggplot2,
gstat,
sp,
rgdal,
raster,
spdep)
#Read shapefile
shp <- st_read("field_boundary.shp")
#Generate data to run interpolation on and project it to the desired CRS
data_sp <- SpatialPointsDataFrame(coords,
data[, c("OM", "data2")],
proj4string = CRS('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'))
#Perform an IDW interpolation:
grd <- SpatialPixels(SpatialPoints(makegrid(data_sp, n=10000)), proj4string = proj4string(data_sp)) #Generate grid for interpolation
plot(grd)
interp <- idw(formula = OM ~ 1, data_sp, grd, idp = 0.5, nmax = 12)
plot(interp) #Makes for a very pretty picture!
#Convert to raster
rast <- raster(interp)
plot(rast)
shp <- st_transform(shp, crs(rast))
#Crop and mask the raster
crop_rast <- crop(rast, shp)
crop_om <- mask(crop_rast, mask = shp)
The error occurs here:
Error in h(simpleError(msg, call)) :
error in evaluating the argument 'x' in selecting a method for function 'addAttrToGeom': sp supports Z dimension only for POINT and MULTIPOINT.
use `st_zm(...)` to coerce to XY dimensions

Error in as.numeric(bbox) : cannot coerce type 'S4' to vector of type 'double'

What this error means??? Maybe an error with coordinate format? Or in the polygon's format/shape?
The script is from Zizka's tutorial "Downloading occurrences from GBIF", in short I need to download occurrences from a specific group of plants that occurs inside this polygon (a multipolygon actually). The polygon is a shapefile that I created in ArcMAP.
This is the script I used to download occurrences from GBIF:
library(countrycode)
library(ConR)
library(devtools)
library(ggmap)
library(mapproj)
library(maps)
library(rgbif)
library(raster)
library(rnaturalearth)
library(sp)
library(tidyverse)
library(viridis)
library(rgdal)
library(rgeos)
library(arulesViz)
library(arules)
tax_key <- name_suggest(q = "Apocynaceae", rank = "Family")
lapply(tax_key$key, "occ_count")
tax_key <- tax_key$key[1]
occ_count(tax_key, country = "BR")
mataatlant <- readOGR('C:/Users/brena/Mata Atlântica/MA GRID', layer = 'MAGrid30')
rgeos::writeWKT(mataatlant)
study_a <- mataatlant
dat_ne <- occ_search(taxonKey = tax_key, return = "data", hasCoordinate = T,
geometry = mataatlant, limit = 50000)
*Error in as.numeric(bbox) :
cannot coerce type 'S4' to vector of type 'double'*
A simplification, but:
You have a a data type mismatch. The s4 object is a shapefile (or an R analogue, such as spatial points/polyongs data frame, or a simple_feature. A double is a field in the data table in ArcMap. You've told R to calculate the shapefile, not the field in the shapefile.

Create bubble plot in R using satellite map

I already created a bubble plot using the following code:
library(ggplot2)
library(sp)
library(raster)
library(maps)
library(mapdata)
library(maptools)
library(gstat)
library(ggmap)
xy <- se_pp[,c("longitude_s", "latitude_s")]
nl <- getData('GADM', country="Netherlands", level=2) #raster data, format SpatialPolygonsDataFrame
# coercing the polygon outlines to a SpatialLines object
spl <- list("sp.lines", as(nl, "SpatialLines"))
SPDF <- SpatialPointsDataFrame(coords=xy, data=se_pp)
projection(SPDF)<- "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0"
coordinates(SPDF)[1:5,] #retrieves spatial coordinates form the dataframe
bubble(SPDF, "Quantity", sp.layout=spl, main="Plaice Quantity (#/km2), end summer (Sand Engine)")
Now I get a map of the Dutch coast containing the bubble plot (via getData).
Unfortunately this is a very simple map.
I would like to have a satellite map of the same area, which shows more detail, to show my bubble plot.
Does anyone know if this is possible?
Thanks.
I am not sure if you still check SO. But, I leave one approach for you. You can play with the values in zoom to identify the best zoom for your purpose. The CRAN manual of ggmap offers you more examples. Please have a look.
map <- get_map(location = 'netherlands', zoom = 7,
source = 'google',
maptype = 'satellite')
ggmap(map)

Gadm map with points layer in R

I have already asked about plotting points dependent on region, but now my question is about overlaying points given by coordinations over gadm map. I want to show different meteostations, using data based on this site or here is data used in code I've tried using such code:
require(ggplot2)
library(maptools)
library(rgdal)
library(RColorBrewer)
library(gpclib)
library(rgeos)
library(PBSmapping)
gpclibPermit()
rus<-load("C://RUS_adm1.RData")
proj4.str <- CRS("+init=epsg:3413 +lon_0=105")
gadm.prj <- spTransform(gadm, proj4.str)
rus<-gadm.prj
met <- read.csv2('C:\\meteo.txt')
cds <- data.frame(
Longitude=met$Long,
Latitude=met$Lat)
k<-as.matrix(cds)
popSP <- SpatialPointsDataFrame(coords=k,met["Elevation"], proj4string=proj4.str)
spplot(popSP, sp.layout=list('sp.polygons', gadm.prj))
, following advice from already mentioneed question, but it ends up with plotting points w/o gadm layer , I guess it's because of non-mentioning regions
Sorry, if question is dumb, but I will be grateful for any help
Here is the answer. Thanks to flowla
Edited code a little bit, I could plot different plot according to elevation.
library(rgdal)
library(raster)
rus <- load("C://RUS_adm1.RData")
popSP <- met <- read.csv2("C://meteo.txt")
for (i in c(3, 4))
popSP[, i] <- popSP[, i] / 1000
coordinates(popSP) <- ~ Long + Lat
projection(popSP) <- projection(gadm)
# Reprojection to EPSG:3413 (see http://www.spatialreference.org/ref/epsg/3413/)
proj4.str <- CRS("+proj=stere +lat_0=90 +lat_ts=70 +lon_0=105 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs")
gadm.prj <- spTransform(gadm, proj4.str)
popSP.prj <- spTransform(popSP, proj4.str)
col_no <- as.factor(as.numeric(cut(popSP.prj$Elevation,
c(0,2500,5000,10000,15000,20000,100000))))
levels(col_no) <- c("<2500", "2500-5000","5000-10000", "10000-15000","15000-20000",">20000" )
color = rainbow(6)
popSP.prj$col_no<-col_no
spplot(popSP.prj, "col_no", sp.layout=list('sp.polygons',cols="ID_0", gadm.prj), col.regions=color, main="Meteostations in Russia", key.space="right")

Resources