【问题标题】:Plotting naturalearth RasterLayer with natural colors using R and ggplot2使用 R 和 ggplot2 用自然颜色绘制 naturalearth RasterLayer
【发布时间】:2021-11-05 11:23:43
【问题描述】:

我正在尝试使用 naturalearthdata 创建南美洲某些地区的地图。创建一个 ggplot2 对象对我来说很重要,因此我可以进一步修改该图并将其与 geom_sf 和 geom_points 结合。我认为最具挑战性的最后一部分已经完成了。

我现在的主要问题是光栅对象被着色,就好像整数值是强度一样。但是,我希望颜色与源中的颜色相同: https://www.naturalearthdata.com/downloads/10m-natural-earth-1/10m-natural-earth-1-with-shaded-relief-water-and-drainages/

我使用以下代码:

library(tidyverse)
library(raster)

hills <- raster("./map_data/NE1_LR_LC_SR_W_DR.tif")

# for the larger dataframe, my RStudio keeps crashing
hills_df <- as.data.frame(hills, xy = T) %>% 
            filter(x >= -90) %>% filter(x <= -55) %>% filter(y <= 5) %>% filter(y >= -30)

ggplot(data = hills_df) +
  geom_raster(aes(x=x, y=y,fill=NE1_LR_LC_SR_W_DR))

问题是数据框只有另一列是整数值。通过将美学设置为fill=value,这个整数被映射为幅度。如何实现源代码中的自然着色?

最好, 塔罗牌

【问题讨论】:

标签: r ggplot2 r-raster


【解决方案1】:

实现此目的的一种方法是创建一个data.frame,其中包含rasterStack 的每个单元格的坐标以及通过rgb 组合的三层的值,请参阅this blog post。

然而,geom_tile 甚至geom_raster 在涉及数万像素时显得非常缓慢。我使用以下解决方法:

  1. 从rasterStack 创建一个 3D 矩阵
  2. 使用rgb 函数将其折叠成二维(如in this SO answer 解释)
  3. 用annotate_raster将RGB值矩阵引入ggplot

代码可以如下:

library(tidyverse)
library(raster)

natearth_map <- 
 raster::stack('./map_data/NE1_LR_LC_SR_W_DR.tif') %>%      # import tiff as rasterStack
  crop(extent(-90, -55, -30, 5)) %>%                        # subset to desired extent
  as.array %>%                                              # convert to 3D array
  `/`(255) %>%                                              # switch to proportions to meet rgb() requirements
  apply(c(1, 2), function(x) rgb(matrix(x, ncol = 3))) %>%  # collapse layers to RGB colors
  annotation_raster(-90, -55, -30, 5)                       # make it a ggplot object

然后你可以像这样将它添加到你的ggplot中。

ggplot(data, aes(x, y)) + natearth_map + geom_point()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    相关资源
    最近更新 更多