I have a dataset with points with x y coordinate, I want to create a grid, and insert this points into de the grid, to visualize better the information of the points.
I have create the grid (I am not sure if is the best way to do it):
# load some spatial data. Administrative Boundary
porto <- getData('GADM', country = 'Portugal', level = 2)
porto$NAME_1
porto <- porto[porto$NAME_2 == "Porto", ]
# check the CRS to know which map units are used
proj4string(porto)
# "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
# Create a grid of points within the bbox of the SpatialPolygonsDataFrame
# colorado with decimal degrees as map units
grid <- makegrid(porto, cellsize = 0.003) # cellsize in map units!
# grid is a data.frame. To change it to a spatial data set we have to
grid <- SpatialPoints(grid, proj4string = CRS(proj4string(porto)))
portoWithin <- SpatialPixels(grid, proj4string = CRS(proj4string(porto)))
plot(porto)
plot(portoWithin, add = T)
I would like to create a heat map with the grid to see in whith area concentrates more points.
Lets say your dataset with points with x y coordinate is this:
#### Data you have that will change the grid values #########
x = c(-8.64, -8.60, -8.65)
y = c(41.14, 41.16, 41.17)
val = c(21,10,30)
df =data.frame(x,y,val)
# Converting to a Spatial Points Data Frame so you can keep the value that you will change within the Grid
points = SpatialPointsDataFrame(coords = df[,1:2],df)
Now that you have your Spatial Point loaded in with the Values that will change your Grid. All you have to do is convert your grid to a Raster, Here is all of your code, with some of my work below it, with comments:
# load some spatial data. Administrative Boundary
porto <- getData('GADM', country = 'Portugal', level = 2)
porto$NAME_1
porto <- porto[porto$NAME_2 == "Porto", ]
# check the CRS to know which map units are used
proj4string(porto)
# "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
# Create a grid of points within the bbox of the SpatialPolygonsDataFrame
# colorado with decimal degrees as map units
grid <- makegrid(porto, cellsize = 0.003) # cellsize in map units!
# grid is a data.frame. To change it to a spatial data set we have to
grid <- SpatialPoints(grid, proj4string = CRS(proj4string(porto)))
portoWithin <- SpatialPixels(grid, proj4string = CRS(proj4string(porto)))
#### Converting the GRID to a Raster
ras_portoWithin <- raster(portoWithin)
## Assigning temporary values to the raster
values(ras_portoWithin) <- 0
## Using the Spatial point file created above (the one with your values) to replace the values of the raster
r1 <- ras_portoWithin
r1[points] <- points$val
plot(r1)
You now have your Grid, with the values given by your points!
Let me know if this helps!
Related
How to convert a single spatial point to a raster object.
I want to create a raster of 0.1 resolution within the domain xmin = 150 xmx=180,ymin=25,ymax=35 and put the values of a datapoint dt point in the raster.
Here is the data and code.
dt<-data.frame(lon=71.85,lat =31.12,val=3)
dt
ras_dom<-raster(xmn=150, xmx=180, ymn=25, ymx=35,
crs="+proj=longlat +datum=WGS84 +no_defs ",
resolution=c(0.1,0.1), vals=NA)
ras_dom
I want to put the value (or values) from dt in the ras_dom so that I have a raster with values for given grids and NA for others.
library(raster)
coordinates(dt) <- ~ lon + lat # Convert data frame to spatial object
result <- rasterize(dt, ras_dom, "val", update = TRUE) # put point in raster
result # The resulting raster with the point added
Because dt in the example is outside the raster, result does not contain it.
I have load the country boundary for Honduras into R and created within it a 2km x 2km grid.
I have then selected 13 random cells from within the grid.
I have then loaded in a vector layer (which is the WWF ecoregions boundaries) which covers the area of Honduras. Within this vector is an attribute called BiomeRealm which describes what type of biomes is present within in polygon of the vector layer (e.g. grasslands or forest).
I have made sure two layers have the same projection.
What I want to do is now extract the area (in KM2) of the attribute BiomeRealm within the 13 random selected cells within the grid I created. My ideal output with would say something like:
BiomeRealm: NT14 - Area - 5km2
NT7 - Area -7km2
How can I do this?
My code so far is:
library(raster)
library(rgdal)
load an admin boudary
shp <- getData(country = "HND", level = 0)
plot(shp)
#transform to a metric coordinate system
shp <- spTransform(shp, CRSobj = "+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs
+ellps=WGS84 +towgs84=0,0,0")
plot(shp)
create a grid within this polygon with specified cell size - what cell size is this?
cs <- c(3.28084, 3.28084)*2000 #cell size of 2km by 2km (1 ft = 3.28084 m)
grdpts <- makegrid(shp, cellsize = cs)
Then, we convert this grid (which basically is a matrix of center points) to a SpatialPoints object
spgrd <- SpatialPoints(grdpts, proj4string = CRS(proj4string(shp)))
This can then be converted into a SpatialPixels object. (Note: adding the subset [shp, ] only selects points within the original polygons)
spgrdWithin <- SpatialPixels(spgrd[shp,])
plot(spgrdWithin, add = T)
change to spatial grid
spgrdWithin <- as(spgrdWithin, "SpatialGrid")
now need to select 13 random grids # SAYS SAMPLE FROM GRID, 13 CELLS, RANDOM)
s <- spsample(spgrdWithin, 13, "random")
plot(s)
now read in the WWF data
HNDWWF <- readOGR('.','HONDURAS_WWF')
plot(HNDWWF)
transform HND WWF layer to same coordiantes as grid
HNDWWFTRANS <- spTransform(HNDWWF, CRSobj = "+proj=utm +zone=32 +datum=WGS84 +units=m
+no_defs +ellps=WGS84 +towgs84=0,0,0")
plot(HNDWWFTRANS)
Your question is not very clear. There may be a much better and more direct way to get at what you are really after. So you may want to clarify. But below is how you might select 13 random cells and intersect these with polygons.
If you are going to use UTM for Honduras, then you need to pick the right zone (16)
library(raster)
v <- getData(country = "HND", level = 0)
crs <- "+proj=utm +zone=16 +datum=WGS84 +units=m"
v <- spTransform(v, CRSobj = crs)
Create a raster with the desired resolution
r <- raster(v, res=2000)
r <- init(r, "cell")
# set areas outside Honduras to NA
r <- mask(r, v)
Sample 13 cells
set.seed(1)
s <- sampleRandom(r, 13)
s
# [1] 44486 48219 55229 72480 41917 71715 77681 59055 57573 35633 42037 40820
#[13] 60238
Now see where these are in the "bioregions" (here using adm1)
bio <- getData(country = "HND", level = 1)
bio <- spTransform(bio, crs)
xy <- xyFromCell(r, s)
extract(bio, xy)[, "NAME_1"]
# [1] "Yoro" "Yoro" "Copán"
# [4] "Francisco Morazán" "Yoro" "Francisco Morazán"
# [7] "Valle" "Francisco Morazán" "Francisco Morazán"
#[10] "Colón" "Gracias a Dios" "Yoro"
#[13] "Olancho"
As for the area, given that we have set the resolution to 2000 m, each cell is 4 km2.
I've got a map with certain number of points on it. I want to (1) calculate the number of points that fall within the raster layer, and (2) extract these points to a data frame.
This is what I've done:
# Packages
library(raster)
library(ggplot2)
library(maptools)
library(tidyverse)
library(dplyr)
library(sp)
# Transform tree ring kml to dataframe
zz<-getKMLcoordinates('treering.kml', ignoreAltitude=TRUE)
l<-as.data.frame(zz)
l<-t(l)
tree <-SpatialPointsDataFrame(l, l,
proj4string = CRS(" +proj=longlat +ellps=WGS84 +datum=WGS84
+no_defs +towgs84=0,0,0"))
# Get world map
data(wrld_simpl)
# Transform World to raster
r <- raster(wrld_simpl, res = 1)
wrld_r <- rasterize(wrld_simpl, r)
# Import permafrost layer to raster
dist1<-raster("PZI.flt")
# Set CRS
dist1 <- projectRaster(from = dist1, crs = CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs
+towgs84=0,0,0"))
# Change colours
micolor <- rev(rainbow(12, alpha = 0.35))
transp <- rainbow(12, alpha = 0)
micolor[1:3] <- transp[1]
# Plot all
plot(wrld_r, col = "lightgrey")
plot(dist1, add=TRUE, legend = F, col = micolor)
plot(tree, add=T, pch = 20, col='black', cex=0.2)
I want to calculate and extract black points located on the colorful parts of this map
First raster::projectRaster does not "set" the projection but, rather reprojects the raster given a transformation and resampling. Given the computational requirements of this it is much faster to reproject the point data using sp::spTransform. Once your data is in the same projection space, you can use raster::extract to extract the raster values. Values out side the raster or in nodata (NA) areas will be assigned NA values. You can drop these observations using a simple NA index with which.
It looks like your data may have a constant value outside of the permafrost. Once you identify what this value is (eg., 0) you can remove these points as well. Here is a worked example. First we add packages and create some example data that is similar to yours.
library(sp)
library(raster)
dist1 <- raster(nrow=20, ncol=20)
dist1[] <- sample(1:10, ncell(dist1), replace=TRUE)
dist1[200:400] <- 0
trees <- sampleRandom(dist1, 100, sp=TRUE)
plot(dist1)
plot(trees,pch=20,col="red",add=TRUE)
Now, we extract the raster values and look at the dimensions of the point object (please note that I do not have to use the sp=TRUE argument in the raster::extract function).
trees#data <- data.frame(trees#data, dist1 = extract(dist1, trees))
dim(trees)
Now we create a row index indicating which rows contain zeros, make sure that we have identified rows (using an if statement) and then remove them. Looking at the object dimensions again, we can see how many points were removed from the original point data.
( idx <- which(trees$dist1 %in% 0) )
if(length(idx) > 0) trees <- trees[-idx,]
dim(trees)
I have create a grid using this code, the grid it is created over the port map:
# load some spatial data. Administrative Boundary
porto <- getData('GADM', country = 'Portugal', level = 2)
porto$NAME_1
porto <- porto[porto$NAME_2 == "Porto",]
# check the CRS to know which map units are used
proj4string(porto)
# "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
# Create a grid of points within the bbox of the SpatialPolygonsDataFrame
# colorado with decimal degrees as map units
grid <- makegrid(porto, cellsize = 0.003) # cellsize in map units!
# grid is a data.frame. To change it to a spatial data set we have to
grid <- SpatialPoints(grid, proj4string = CRS(proj4string(porto)))
portoWithin <-
SpatialPixels(grid, proj4string = CRS(proj4string(porto)))
#### Converting the GRID to a Raster
ras_portoWithin <- raster(portoWithin)
plot(porto)
plot(portoWithin, add = T)
Now I want to insert SpatialPonits in the grid, so that I can discretize the data.
The result would be to see in each grid cell how many points there are, to work with cells instead of with points.
The dataSet of points are SpatialPoints which correspond to GPS coordinates:
[,1] [,2]
[1,] -8.574678 41.15195
[2,] -8.574705 41.15194
[3,] -8.574696 41.15193
[4,] -8.574660 41.15196
[5,] -8.574723 41.15193
[6,] -8.574714 41.15192
I have a grid of the map of Porto, I would like to be able to insert in the grid the points to discretize them. In this way to see how many points are in each cell depending on the time.
This is the code of the grid:
#latitudS and longitudS are coordinates x Y
x = longitudS
y = latitudS
df = data.frame(x, y)
# Converting to a Spatial Points Data Frame so you can keep the value that you will change within the Grid
points = SpatialPointsDataFrame(coords = df[, 1:2], df)
# load some spatial data. Administrative Boundary
porto <- getData('GADM', country = 'Portugal', level = 2)
porto$NAME_1
porto <- porto[porto$NAME_2 == "Porto",]
# check the CRS to know which map units are used
proj4string(porto)
# "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
# Create a grid of points within the bbox of the SpatialPolygonsDataFrame
# colorado with decimal degrees as map units
grid <- makegrid(porto, cellsize = 0.003) # cellsize in map units!
# grid is a data.frame. To change it to a spatial data set we have to
grid <- SpatialPoints(grid, proj4string = CRS(proj4string(porto)))
portoWithin <-
SpatialPixels(grid, proj4string = CRS(proj4string(porto)))
#### Converting the GRID to a Raster
ras_portoWithin <- raster(portoWithin)
## Assigning temporary values to the raster
values(ras_portoWithin) <- 0
## Using the Spatial point file created above to replace the values of the raster
r1 <- ras_portoWithin
plot(porto)
plot(portoWithin, add = T)
The idea is that for each cell the number of points will be output depending on the time in which the points have been recorded.
Also ask if there would be any way to transfer that grid to a leaflet, so you can see it on a map.
Thanks!