您可以使用ggpmisc 将绘图和表格放置在空绘图上。
为方便定位,空图坐标设置为(0,1)范围。
您可以定义小标题中每个对象的位置(见下文)并使用以下参数调整大小/位置:
-
vp.height 和 vp.width 定义每个图的宽度和高度(从 0 到 1 = 100%)
-
hjust 和 vjust 定义表格如何与其位置对齐:0 是左/下调整,1 是上/右调整
set.seed(1234)
library(dplyr)
library(tidyr)
library(ggplot2)
library(ggpmisc)
df <- data.frame(height1 = round(rnorm(200, mean=60, sd=15)), height2 = round(rnorm(200, mean=55, sd=10)))
tb <- df %>% pivot_longer(c('height1', 'height2'), names_to = "Group", values_to = "value") %>%
group_by(Group) %>%
summarize(Samples = n(), Median=median(value, na.rm=T), Pctl_10th=quantile(value, 0.1, na.rm=T))
p <- df %>% pivot_longer(c('height1', 'height2'), names_to = "Group", values_to = "value") %>%
ggplot(aes(value, colour = Group)) +
stat_ecdf()
# x and y values define the position of the lower left corner of eah object
data.plot <- tibble(x = 0, y = 0, p = list(p ))
data.tb <- tibble(x = 0.6, y = 0, tbl = list(tb))
# Set up the plot
# vp.width defines the relative width of the plot : here = 70% (including legend)
# vp.height defines the relative height of the plot : here = 80%
# hjust defines table horizontal alignement, set to 0 so that x controls left position
# vjust defines table vertical alignement, set to 0 so that y control bottom position
# On the side of the plot
ggplot() + xlim(c(0,1)) + ylim(c(0,1)) + theme_void() +
geom_plot(data = data.plot, aes(x, y, label = p,vp.width = .7,vp.height = 0.8))+
geom_table(data=data.tb, aes(x,y,label = tbl,hjust=0,vjust=0))
# Inside the plot
data.tb <- tibble(x = 0.4, y = 0.1, tbl = list(tb))
ggplot() + xlim(c(0,1)) + ylim(c(0,1)) + theme_void() +
geom_plot(data = data.plot, aes(x, y, label = p,vp.width = 0.95,vp.height = 0.8))+
geom_table(data=data.tb, aes(x,y,label = tbl,hjust=0,vjust=0))
请注意,ggmisc 不控制表格宽度,因此很难将绘图边框与表格边框完美对齐,必须根据图形大小手动完成。