【问题标题】:Avoiding code repetition in ggplot: adding various geom_sf plots避免ggplot中的代码重复:添加各种geom_sf图
【发布时间】:2019-04-01 23:57:48
【问题描述】:

根据关于箱线图的this 问题和关于制作印度地图的my own question,在处理地图的各个层时,避免 ggplot 中代码重复的好方法是什么?

下面是一个 reprex 。我认为最简单的方法是: 1.保存带有州和国界的基本地图 2.添加区层(显示变量)。

想象为几十个变量重复第 2 步。

library(ggplot2)
library(sf)
library(raster)

# Download district and state data (should be less than 10 Mb in total)

distSF <- st_as_sf(getData("GADM",country="IND",level=2))

stateSF <- st_as_sf(getData("GADM",country="IND",level=1))

# Add country border

countryborder <- st_union(stateSF)

# STEP 1: Basic plot

basicIndia <- ggplot() +
  geom_sf(data = stateSF, color = "white", fill = NA) +
  geom_sf(data = countryborder, color = "blue", fill = NA) +
  theme_dark()

# STEP 2: Adding the data layer underneath so it doesn't cover the other borders

indiaMap$layers <- c(geom_sf(data = distSF, fill = "red")[[1]], indiaMap$layers[[2:3]])

indiaMap$layers <- c(geom_sf(data = distSF, fill = "gold")[[1]], indiaMap$layers[[2:3]])

indiaMap

但是,这样一来,就无法对附加层进行哪怕是很小的修改,例如添加不同的标题。以下显然行不通,但说明了我的观点。

basicIndia$layers <- c(
  geom_sf(data = distSF, aes(fill = GINI), color = "white", size = 0.2)[[1]] +
    labs(title = "Gini coefficient"), 
                       basicIndia$layers)

我是否以错误的方式解决问题?这是不能做的事情吗?

【问题讨论】:

    标签: r ggplot2 maps sp sf


    【解决方案1】:

    解决问题的另一种方法是使用ggplot_build()

    使用以下方法创建ggplot_build 对象:

    indiaBuild <- ggplot_build(basicIndia)
    

    我们现在可以使用以下步骤来代替您的第 2 步:

    indiaBuild$plot$layers <- c(indiaBuild$plot$layers,
                                geom_sf(data=distSF, fill='gold')[[1]])
    

    您可以更改 ggplot_build 对象的各个部分,然后包括标题:

    indiaBuild$plot$labels$title <- 'Gini coefficient'
    

    完成后,您可以使用 p &lt;- indiaBuild$plot 仅提取绘图

    【讨论】:

      猜你喜欢
      • 2020-11-23
      • 2016-09-18
      • 1970-01-01
      • 2014-03-07
      • 1970-01-01
      • 2018-07-07
      • 1970-01-01
      相关资源
      最近更新 更多