从光栅图包到ggplot2

时间:2019-01-20 18:04:40

标签: r ggplot2 maps

我的问题:我想绘制一个通过rastermap包和ggplot2获得的地图。

在搜索ggmap软件包的替代品时,我发现了rastermap软件包,该软件包提供了一种从外部来源获取地图的简便方法。 readme提供了一个非常简单的示例:

# install.packages("devtools")
devtools::install_github("hadley/rastermap")

houston <- fetch_region(c(-95.80204, -94.92313), c(29.38048, 30.14344),
  stamen("terrain"))
houston
plot(houston)

问题出在我是否尝试使用ggplot进行绘制。到目前为止,我已经尝试了几种方法,但是似乎都没有。可能吗?有想法吗?

2 个答案:

答案 0 :(得分:1)

rastermap生成十六进制字符串(#RRGGBB格式)的颜色矩阵。将其转换为空间数据的更常见形式(一种多波段光栅砖,其中红色,绿色和蓝色具有单独的图层)可能是最简单的。

我们可以编写一个简短的辅助函数,以将十六进制字符串转换为单独的整数值(即,这与rgb()函数相反):

un_rgb = function (x) {
  x = unlist(str_split(x, ''))
  r = paste0(x[2], x[3])
  g = paste0(x[4], x[5])
  b = paste0(x[6], x[7])
  strtoi(c(r,g,b), 16)
}

使用此功能,我们将栅格地图矩阵转换为三波段栅格块:

library(raster)    
m = as.matrix(houston)
l=lapply(m[], un_rgb)
r=g=b=matrix(, dim(m)[1], dim(m)[2])
r[] = sapply(l, function(i) i[1])
g[] = sapply(l, function(i) i[2])
b[] = sapply(l, function(i) i[3])
rgb.brick = brick(raster(r), raster(g), raster(b))

并将新栅格的范围设置为原始栅格地图的范围

extent(rgb.brick) = extent(matrix(unlist(attributes(houston)$bb), nrow=2))

现在,我们有了一种更常见的栅格对象形式,我们可以使用它来做各种事情。例如,我们可以使用library(RStoolbox)将其绘制在ggplot中:

ggRGB(rgb.brick, r=1, g=2, b=3)

enter image description here

或者我们可以将其另存为图像,以用作ggplot中的注释背景:

png('test.png', dim(rgb.brick)[2], dim(rgb.brick)[1])
  plotRGB(rgb.brick, 1, 2, 3)
dev.off()

img <- png::readPNG("test.png")
gr <- grid::rasterGrob(img, interpolate=TRUE)
ggplot() + annotation_custom(gr, -Inf, Inf, -Inf, Inf)

enter image description here

答案 1 :(得分:0)

您为什么要选择其他方法?您可以从获得雄蕊图:

library(ggmap)
ggmap(get_stamenmap(c(-95.80204, 29.38048, -94.92313, 30.14344))) +
# some points to plot
geom_point(aes(x = seq(-95.5, -95.2, 0.1), y = seq(29.7, 30, 0.1)), color = "red")

1