簡體   English   中英

將ggplot2網格線移動到頂層但保留面板背景

[英]Move ggplot2 gridlines to top layer but keep panel background

使用帶有ggplot2sf包,網格線用於繪制刻度。 通過將panel.ontop設置為TRUE ,可以在地圖上放置經緯網:

library(sf)
library(ggplot2)

nc <- st_read(system.file("shape/nc.shp", package="sf"))

ggplot() +
    geom_sf(data = nc, fill='white') +
    coord_sf(expand = T) +
    theme(panel.border = element_rect(color = 'black', fill = NA),
          panel.background = element_blank(),
          panel.ontop = T,
          plot.background = element_rect(fill = "#ddefff"),
          axis.ticks = element_blank(),
          axis.text = element_blank()) +
    ggtitle("NC")

在此輸入圖像描述

然而,我想要的是能夠設置繪圖區域的背景顏色,通常使用panel.background來完成。 這顯然不適用於此,因為它將涵蓋地圖。

期望的結果:

在此輸入圖像描述

我最初的想法是,我可以先添加geom_rect面板區域的確切大小,但我不確定如何獲得這些尺寸。 如何將網格線保持在頂部,但仍然具有獨特的面板背景顏色?

編輯

從下面的@sebdalgarno中得到了很好的答案,我發現我們可以使用expand_range來解決擴展問題(如ggplot2內部做的那樣):

bb <- st_bbox(nc)
bb[c(1,3,2,4)] <- c(scales::expand_range(c(bb$xmin, bb$xmax), mul = 0.05),
                    scales::expand_range(c(bb$ymin, bb$ymax), mul = 0.05))
bb <- bb %>% st_as_sfc() %>% st_sf()

現在這給出了與設置coord_sf(expand = T)相同的擴展因子。

此解決方案適用於expand = F:

按照你的geom_rect建議,將bbox轉換為sf多邊形

bb <- st_bbox(nc) %>% st_as_sfc() %>% st_sf()

並使用geom_sf繪圖

ggplot() +
  geom_sf(data = bb, fill = 'grey') +
  geom_sf(data = nc, fill='white') +
  coord_sf(expand = F) +
  theme(panel.border = element_rect(color = 'black', fill = NA),
        panel.background = element_blank(),
        panel.ontop = T,
        plot.background = element_rect(fill = "#ddefff"),
        axis.ticks = element_blank(),
        axis.text = element_blank()) +
  ggtitle("NC")

如果你可以弄清楚如何手動擴展相同數量的bbox多邊形,這可以使用expand = T.

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM