Построение полигонов с растрами в base R, ggplot2 или levelplot - PullRequest
0 голосов
/ 05 мая 2020

Я пытаюсь построить в R растровый слой с линиями / полигональными объектами в R, и каждый раз я терплю неудачу с ошибками. Я пытался сделать это в base R, ggplot2 и используя levelplot, но не могу получить правильный результат.

Исходные данные можно найти здесь .

Что мне нужно сделать на графике (все на одном графике), так это: 1) увеличить определенную область, определенную как NIG. T 2) Отобразить растровые r значения на шкале с cuts интервалами. 3) Постройте границы страны (shpAfr в base R и ggplot2 или world.outlines.sp в levelplot). 4) Наконец, добавьте слой многоугольника shpWater (с заливкой и контурами col="blue").

library(raster)
library(maptools)
library(rasterVis)
library(viridis)
library(sf)
library(rgdal)
library(ggplot2)

r <- raster("raster_example.tif")
crs(r) <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +to wgs84=0,0,0"
NIG <- c(2,14.5,4,14)
Reg_name <- "Nigeria"

shpAfr <- readOGR(dsn="Africa.shp")
proj4string(shpAfr) # describes data’s current coordinate reference system
#st_read(system.file("shape/nc.shp", package="sf"))

# Import water polygon
shpWater <- readOGR(dsn="waterbodies_africa.shp")
shpWater.count <- nrow(shpWater@data)
shpWater$id <- 1:shpWater.count
shpWater.fort <- fortify(shpWater, region='id')

# Import Africa admin map
shpAfr <- readOGR(dsn="Africa.shp")
shpAfr.count <- nrow(shpAfr@data)
shpAfr$id <- 1:shpAfr.count
shpAfr.fort <- fortify(shpAfr, region='id')

# Set colour intervals for plotting:
cuts=seq(0,1,0.1) #set breaks

Пробуя базовый R, моя проблема в том, что я могу получить заливку формы воды правильного цвета (заливка и контур должны быть синими). Если я попытаюсь построить wrld_simpl и shpWater как polygon (), у меня возникнут еще большие проблемы.

plot(r, xlim = NIG[1:2], ylim = NIG[3:4],
     breaks=cuts, col = rev(plasma(11)))
lines(wrld_simpl,lwd = 1.5)
lines(shpWater, col="blue") # works but cannot fill the polygon
polygon(shpWater, col = "blue", border = "blue") # getting error here
Error in as.double(y) : 
  cannot coerce type 'S4' to vector of type 'double'

Хорошо, теперь я пробую ggplot2, но я не могу найти способ добавить сюда растр без ошибок.

lon <- seq(r@extent@xmin,r@extent@xmax,
           (r@extent@xmax-r@extent@xmin)/r@ncols)
lat <- seq(r@extent@ymin,r@extent@ymax,
           (r@extent@ymax-r@extent@ymin)/r@nrows)

Plot1 <- ggplot()+
  geom_polygon(aes(x = long, y = lat, group=id),
               data = shpAfr.fort, color ="grey27", fill ="grey",
               alpha = .4, size = .2)+
  geom_raster(data = test, aes(fill=values))+ ## here it goes bad
  #geom_tile(data=test_df, aes(x=x, y=y, fill=value), alpha=0.8) + 
  #scale_fill_viridis() +
  geom_polygon(aes(x = long, y = lat, group=id),
               data = shpWater.fort, color ="lightskyblue2", fill ="lightskyblue2",
               size = .2)+coord_equal()+
  theme_minimal()+
  coord_map(xlim = Region[[3]][1:2],ylim = Region[[3]][3:4])

plot(Plot1)

Наконец, я попробовал график уровней, и СНОВА не удалось.

mapTheme <- rasterTheme(region = rev(brewer.pal(10, "RdBu")))

# Get world outlines:
world.outlines <- map("world", plot=FALSE)
world.outlines.sp <- map2SpatialLines(world.outlines, proj4string = CRS("+proj=longlat"))

# Plot raster and polygon:
Plot2 <- levelplot(r,par.settings = mapTheme,pretty=TRUE,margin = F,
          xlim = NIG[1:2],ylim = NIG[3:4],
          col.regions=colorRampPalette(c("light blue","blue", "red")),
          main=paste0("test")) + layer(sp.lines(world.outlines.sp, col = "black", lwd = 0.5))
plot(Plot2 + layer(sp.lines(world.outlines.sp, col = "black", lwd = 0.5))
#Error: Attempted to create layer with no stat.

Мои результаты на данный момент: 1) первое изображение не имеет многоугольников, заполненных синим 2) второе изображение имеет четкие очертания мира не в нужном месте: enter image description here enter image description here

...