我想使用plot_grid或类似的函数绘制多个具有注释层的ggplot,并在绘图时保持注释层的相对大小/位置相同。以下是一个示例:
# 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()
答案 0 :(得分:1)
使用ggsave()
并定义适当的width
和height
对我有用;
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)