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

问题描述 投票:1回答:1

我想使用plot_grid或类似函数绘制具有注释图层的多个ggplots,并在绘图时保持注释图层的相对大小/位置相同。以下是一个例子:

# 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()
             
r ggplot2 gridextra
1个回答
1
投票

使用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)
https://i.stack.imgur.com/5YaNL.jpg
© www.soinside.com 2019 - 2024. All rights reserved.