4

I am having issues plotting true to geographic extent pixels in R. the files come with a list of daily single coordinates and pixel size (area). There is also a Z element separate from this. The data structure looks this way:

 X <- c(1,3,6,7)
 Y <- c(3,2,7,8)
 Z <- c(38,23,12,12)
 Area <- c(32,23,45,67)

The X and Y are in degrees longitude and latitude while the area is in square kilometres. I create the point features easily using:

library(sp)
A <- cbind(X,Y,Z,Area)
B <- SpatialPoints(A)

I plot these easily using the area values to determine the "cex" for plotting. The Z column is intensity and I use these values to determine the colours . How do I create spatial polygons features using the areas for each point in R? I would be using these points to create gridded rasters.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Joke O.
  • 515
  • 6
  • 29

2 Answers2

5

This should do the trick:

library(rgeos)      ## for gBuffer()
library(raster)     ## for bind()

ww <- sqrt(B$Area)/2  ## Widths of buffers needed to produce desired areas    

pp <- list()
for(i in seq_along(B)) {
    pp[i] <- gBuffer(B[i], width=ww[i], quadsegs=1, capStyle="SQUARE")
}
PP <- do.call(bind, pp)

## Check that it worked
plot(PP)
plot(B, add=TRUE)
text(B, labels=1:4, adj=c(-1,0), col="red")

enter image description here

Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
0

Just to update this a bit, here is an sf solution.

Function to create the square buffers

bSquare <- function(x, a) {
  a <- sqrt(a)/2
  return( sf::st_buffer(x, dist = a, nQuadSegs=1, 
                        endCapStyle = "SQUARE") )
}

Some example data

library(sf)
xy <- st_as_sf(data.frame(x = c(1,3,6,7),
               y = c(3,2,7,8), z = c(38,23,12,12),
               area = c(32,23,45,67)),
               coords = c("x", "y"), 
               agr = "constant") 

With variable buffer

sb.var <- bSquare(xy, xy$area)
  plot(st_geometry(sb.var))
    plot(st_geometry(xy), pch=20, add=TRUE)

variable

With fixed buffer

sb <- bSquare(xy, 32)
  plot(st_geometry(sb))
    plot(st_geometry(xy), pch=20, add=TRUE)

fixed

Jeffrey Evans
  • 2,325
  • 12
  • 18