[英]Move ggplot2 gridlines to top layer but keep panel background
使用帶有ggplot2
的sf
包,網格線用於繪制刻度。 通過將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.