在R中的ggplot2中覆盖地图上的栅格图层?

时间:2017-11-04 22:25:33

标签: r ggplot2 raster

我正在尝试将栅格图层叠加到ggplot中的地图上。栅格图层包含来自卫星标记的每个时间点的似然表面。我还想在栅格图层上设置累积概率(95%,75%,50%)。

我已经想出如何在ggplot地图上显示栅格图层,但坐标彼此不对齐。我尝试让每个都有相同的投影,但它似乎没有工作...我希望它们都适合我的模型的边界(xmin = 149,xmax = 154,ymin = -14,ymax = -8.75

附件是我的r代码和数字结果:

#load data
ncname <- "152724-13-GPE3"
ncfname <- paste(ncname, ".nc", sep = "")
ncin <- nc_open(ncfname)

StackedObject<-stack("152724-13-GPE3.nc", varname = "monthly_residency_distributions")
MergedObject<-overlay(StackedObject,fun=mean ) 
MergedObject[is.na(MergedObject)]<-0 
Boundaries<-extent(c(149, 154, -14, -8.75)) 
ExtendedObject<-extend(MergedObject, Boundaries) 
Raster.big<-raster(ncol=1200,nrow=900,ext=Boundaries) 
Raster.HR<-resample(x=ExtendedObject, y=Raster.big, method="bilinear") 
Raster.HR@data@values<- Raster.HR@data@values/sum(Raster.HR@data@values) 
RasterVals<-sort(Raster.HR@data@values)
Raster.breaks <- c(RasterVals[max(which(cumsum(RasterVals)<= 0.05 ))], RasterVals[max(which(cumsum(RasterVals)<= 0.25 ))], RasterVals[max(which(cumsum(RasterVals)<= 0.50 ))], 1)
Raster.cols<-colorRampPalette(c("yellow","orange","red"))
RasterCols<- c(Raster.cols(3))

#Create Map
shape2 <- readOGR(dsn = "/Users/shannonmurphy/Desktop/PNG_adm/PNG_adm1.shp", layer = "PNG_adm1")
map<- crop(shape2, extent(149, 154, -14, -8.75))
projection(map)<- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")

p <- ggplot() + geom_polygon(data = map, aes(x = long, y = lat, group = group), color = "black", size = 0.25) + coord_map()

projection(Raster.HR)<- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")

#plot raster and ggplot 

par(mfrow=c(1,1))
plot(p)
par(mfrow=c(1,1), new = TRUE)
plot(Raster.HR, col=RasterCols, breaks=Raster.breaks, legend = NULL, bbox(map)) 

enter image description here

请告诉我是否还有其他一揽子/一行代码我应该这样做!感谢任何帮助

1 个答案:

答案 0 :(得分:4)

好的我明白了。您希望在ggplot上绘制多个栅格图层,或者希望栅格对象位于背景多边形对象上。 rasterVis::gplot的问题在于它直接绘制栅格并且不允许在其下添加另一个栅格。您提醒我,我已经有了这个需求并修改了函数gplot以将数据检索为tibble,以便您可以使用dplyr然后ggplot2尽可能多地使用它。 。感谢您的提醒,我将其添加到我当前的github库中供以后使用!
让我们使用一个可重现的例子来展示这个功能:

创建数据集

  • 创建一个世界地图,作为Raster用作背景栅格地图
  • 创建数据栅格,此处距离点(限制为最大距离)

代码:

library(raster)

# Get world map
library(maptools)
data(wrld_simpl)
# Transform World as raster
r <- raster(wrld_simpl, res = 1)
wrld_r <- rasterize(wrld_simpl, r)

# Lets create a raster of data
pt1 <- matrix(c(100,0), ncol = 2)
dist1 <- distanceFromPoints(r, pt1)
values(dist1)[values(dist1) > 5e6] <- NA
plot(dist1)

# Plot both
plot(wrld_r, col = "grey")
plot(dist1, add = TRUE)

Both Raster data on classic plot

提取(部分)栅格值并转换为tibble

的函数
#' Transform raster as data.frame to be later used with ggplot
#' Modified from rasterVis::gplot
#'
#' @param x A Raster* object
#' @param maxpixels Maximum number of pixels to use
#'
#' @details rasterVis::gplot is nice to plot a raster in a ggplot but
#' if you want to plot different rasters on the same plot, you are stuck.
#' If you want to add other information or transform your raster as a
#' category raster, you can not do it. With `SDMSelect::gplot_data`, you retrieve your
#' raster as a tibble that can be modified as wanted using `dplyr` and
#' then plot in `ggplot` using `geom_tile`.
#' If Raster has levels, they will be joined to the final tibble.
#'
#' @export

gplot_data <- function(x, maxpixels = 50000)  {
  x <- raster::sampleRegular(x, maxpixels, asRaster = TRUE)
  coords <- raster::xyFromCell(x, seq_len(raster::ncell(x)))
  ## Extract values
  dat <- utils::stack(as.data.frame(raster::getValues(x))) 
  names(dat) <- c('value', 'variable')

  dat <- dplyr::as.tbl(data.frame(coords, dat))

  if (!is.null(levels(x))) {
    dat <- dplyr::left_join(dat, levels(x)[[1]], 
                            by = c("value" = "ID"))
  }
  dat
}

在ggplot

中绘制多个栅格

您可以使用gplot_data将任何栅格转换为tibble。然后,您可以使用dplyr添加任何修改,并使用ggplotgeom_tile上进行绘图。有趣的是,只要geom_tile选项具有可比性,您就可以根据需要使用fill多个不同的栅格数据。否则,您可以使用以下技巧删除背景栅格地图中的NA值,并使用唯一的fill颜色。

# With gplot_data
library(ggplot2)

# Transform rasters as data frame 
gplot_wrld_r <- gplot_data(wrld_r)
gplot_dist1 <- gplot_data(dist1)

# To define a unique fill colour for the world map,
# you need to remove NA values in gplot_wrld_r which 
# can be done with dplyr::filter
ggplot() +
  geom_tile(data = dplyr::filter(gplot_wrld_r, !is.na(value)), 
            aes(x = x, y = y), fill = "grey20") +
  geom_tile(data = gplot_dist1, 
            aes(x = x, y = y, fill = value)) +
  scale_fill_gradient("Distance",
                      low = 'yellow', high = 'blue',
                      na.value = NA) +
  coord_quickmap()

Multiple raster on the same ggplot

在多边形上绘制栅格

当然,将背景地图作为多边形对象,这个技巧还可以让你在它上面添加光栅:

wrld_simpl_sf <- sf::st_as_sf(wrld_simpl)

ggplot() +
  geom_sf(data = wrld_simpl_sf, fill = "grey20",
          colour = "white", size = 0.2) +
  geom_tile(data = gplot_dist1, 
            aes(x = x, y = y, fill = value)) +
  scale_fill_gradient("Distance",
                      low = 'yellow', high = 'blue',
                      na.value = NA)

Raster over polygons in ggplot

编辑:gplot_data现在位于这个简单的R包中:https://github.com/statnmap/cartomisc