如何使用绘图设备大小缩放 ggplot annotation_custom 层?

How to scale ggplot annotation_custom layer with plotting device size?

我想使用 plot_grid 或类似函数绘制多个具有注释层的 ggplot,并在绘制时保持注释层的相对 size/position 相同。下面是一个例子:

# Generate scatter plot with ggplot.
library(ggplot2)
data <- data.frame(x = rnorm(1000),
                   y = rnorm(1000))
p1 <- ggplot(data, aes(x = x, y = y)) + geom_point()


# Build annotation table with gridExtra::tableGrob().
library(gridExtra)
mytable <- summary(data)
tab <- tableGrob(mytable, rows=NULL, theme=tt)

# Extract x and ylims for positioning table with ggplot_build(). 
xrange <- unlist(ggplot_build(p1)$layout$panel_params[[1]][1])
yrange <- unlist(ggplot_build(p1)$layout$panel_params[[1]][8])
xmin = min(xrange)
xmax = max(xrange)
xdelta = xmax-xmin
ymin = min(yrange)
ymax = max(yrange)
ydelta = ymax-ymin

# Add annotation table to plot.
p2 <- p1 + annotation_custom(tab, xmin = xmin-0.55*xdelta, xmax,
                                  ymin = ymin+0.55*ydelta, ymax)
p2
              
# Generate figure with multiple plots using cowplot::plot_grid(). 
library(cowplot)
fig <- plot_grid(p2,p2,p2,p2, labels = "auto")
fig 
     

请帮我在最终图中保持注释层的比例和位置相同。理想情况下,这可以按照我的示例的顺序完成:制作一个带注释的绘图,绘制多个绘图,但我理解这是否不可能。

编辑。

缩放绘图设备似乎无法解决问题。

## Exploring changing the device size.

# I think the default device size is 7x7 inches. 
png("default_size.png",width = 7, height = 7, res = 300, units = "in")
p2
dev.off()
             
# Plot2x
png("2x_size.png",width = 14, height = 14, res = 300, units = "in")
p2
dev.off()
             
# Plot3x
png("3x_size.png",width = 21, height = 21, res = 300, units = "in")
p2
dev.off()
             

使用 ggsave() 并定义适当的 widthheight 这对我有用;

library(ggplot2)
library(gridExtra)
set.seed(123) #make the result reproducible

#avoid using data as your dataframe name
mydf <- data.frame(x = rnorm(1000),
                   y = rnorm(1000))  

plt <- ggplot(mydf, aes(x = x, y = y)) + geom_point()

mytable <- summary(mydf)
mytab <- tableGrob(mytable, rows=NULL) #theme = tt? tt is not defined!

xrange <- unlist(ggplot_build(plt)$layout$panel_params[[1]][1])
yrange <- unlist(ggplot_build(plt)$layout$panel_params[[1]][8])
xmin = min(xrange)
xmax = max(xrange)
xdelta = xmax-xmin
ymin = min(yrange)
ymax = max(yrange)
ydelta = ymax-ymin

tplt <- plt + annotation_custom(tab, xmin = xmin-0.55*xdelta, xmax, 
                                     ymin = ymin+0.55*ydelta, ymax) 

mygrobs <- grid.arrange(tplt, tplt, tplt, tplt,
                        nrow = 2)

ggsave("filename.jpeg", plot = mygrobs,
       scale = 1, width = 15, height = 10, units = "in",
       dpi = 300)