如何在不改变插图本身的宽度和高度的情况下灵活定位inset
using ?ggpmisc
library(tidyverse)
library(sf)
library(ggpmisc)
#data
nc <- st_read(system.file("gpkg/nc.gpkg", package = "sf"), quiet = TRUE) %>%
st_transform(st_crs(4326)) %>%
st_cast('POLYGON')
#create timeseries data
nc_2 <- rbind(nc %>% mutate(timepoint = 1), nc %>% mutate(timepoint = 2))
#create base plot
nc_2_base <- ggplot(data = nc_2) +
geom_sf(aes(fill = BIR74)) +
coord_sf(xlim = c(-80, -76),
ylim = c(32, 37), expand = FALSE)
#facet plot
nc_2_main <- nc_2_base + facet_wrap(~timepoint, dir = "h", ncol = 2)
#extract number of timepoints
nmax_rep_nc <- length(unique(nc_2$timepoint))
#create insets
insets_nc <- lapply(seq_len(nmax_rep_nc), function(i) {
nc_2_base + ggforce::facet_wrap_paginate(~ timepoint, nrow = 1, ncol = 1, page = i) +
coord_sf(xlim = c(-79.5, -78.5), ylim = c(34.5, 35.5)) +
theme(strip.background = element_blank(),
strip.text = element_blank(),
axis.title = element_blank(),
plot.background = element_blank(),
legend.position = "none")
})
要定位插图,您需要创建一个tibble
with x
,y
指示您想要的位置。在这里,我希望它们位于左下角,因此指定x = 0.0
和y = 0
(x
,y
可以0 - 1
来自这里的小插图),并且我希望插图的大小是主图的 50%(vp.width = 0.5, vp.height = 0.5
):
insets_nc_tibble <- tibble(x = rep(0.0, nmax_rep_nc),
y = rep(0.0, nmax_rep_nc),
plot = insets_nc,
timepoint = unique(nc_2$timepoint))
#add inset to plot:
nc_2_main +
geom_rect(xmin = -79.5, xmax = -78.5, ymin = 34.5, ymax = 35.5,
fill = NA, colour = "red", size = 1.5) +
geom_plot_npc(data = insets_nc_tibble,
aes(npcx = x, npcy = y, label = plot,
vp.width = 0.5, vp.height = 0.5))
这产生了这个情节:
(0, 0)
但是我想要的左下角的插图不正确。我怎样才能保持这个尺寸的插图但移动它,让它直接在角落里?
如果我减小插图的大小,它似乎会有所帮助,但这完全是反复试验,我不想减小插图的大小。
#reduce size
nc_2_main +
geom_rect(xmin = -79.5, xmax = -78.5, ymin = 34.5, ymax = 35.5,
fill = NA, colour = "red", size = 1.5) +
geom_plot_npc(data = insets_nc_tibble,
aes(npcx = x, npcy = y, label = plot,
vp.width = 0.5, vp.height = 0.25))
这会产生这个定位更好但不是我想要的正确大小的图:
请注意,您也可以按字符串指定角点,但这无济于事:
#insets_nc_tibble <- tibble(x = rep("left", nmax_rep_nc),
# y = rep("bottom", nmax_rep_nc),
# plot = insets_nc,
# timepoint = unique(nc_2$timepoint))
我不明白如何改变大小,改变位置。我认为指定x, y = 0, 0
意味着插图的左下角应该设置为,0, 0
但这里似乎不是这种情况?
有任何想法吗?
谢谢