【发布时间】:2021-05-08 17:44:42
【问题描述】:
如何使用ggpmisc灵活定位inset而不改变插图本身的宽度和高度?
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,其中x、y 指示您想要的位置。在这里,我希望它们位于左下角,因此指定 x = 0.0 和 y = 0(x,y 可以是来自小插图 here 的 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))
这个问题是对我之前的回答和其他人here的跟进。
我不明白如何改变大小,改变位置。我认为指定x, y = 0, 0 意味着插图的左下角应该设置为0, 0,但这里似乎不是这样?
有什么想法吗?
谢谢
【问题讨论】:
标签: r ggplot2 facet facet-wrap ggpmisc