代码之家  ›  专栏  ›  技术社区  ›  Tito Sanz

从rastermap包到ggplot2

  •  1
  • Tito Sanz  · 技术社区  · 6 年前

    我的问题是:我想画一张通过 rastermap 包装用 ggplot2 .

    寻找替代方案 ggmap 我找到的包裹 光栅地图 提供从外部来源获取地图的简单方法的包。这个 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 回复  |  直到 6 年前
        1
  •  1
  •   dww Jarretinha    6 年前

    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)
    }
    

    使用此函数,我们将Rastermap矩阵转换为三段光栅砖:

    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))
    

    并将新光栅的范围设置为原始Rastermap的范围。

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

    既然我们有了一个更常见的光栅对象的形式,我们可以用它做各种各样的事情。例如,我们可以使用 library(RStoolbox) :

    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

        2
  •  0
  •   Roman    6 年前

    你为什么要另一个选择?你可以从那里得到雄蕊图 :

    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