我试图在pdf中输出两个ggplot图列表 . 我想生成一个pdf文件,其中我左边有一个列表,右边有一个列表(理想情况下是4个2格的多个页面) .
我将所有代码都包含在内,但是重要的部分是绘图 .
如果我在R studio中运行它,我会在图表预览中看到我想要的内容,但是如果我包含在pdf(文件名)和dev.off之间打印图表的循环,我会得到一个包含所有图表的pdf文件 . 彼此 . 我让它发挥作用 .
library(ggplot2)
library(tools)
library(gridExtra)
library(grid)
data_ahl<-read.csv("data_AHL.txt", header = TRUE)
data_none<-read.csv("data_none.txt", header = TRUE)
data_ahl$Concentration <- as.factor(data_ahl$Concentration)
data_none$Concentration <- as.factor(data_none$Concentration)
data <- rbind(data_ahl, data_none)
plasmid_list <- unique(data_ahl$Plasmid)
plot_list_atc <- list()
plot_list_none <- list()
j = 1
for (receiver in plasmid_list){
print(receiver)
upperbound <- max(data_ahl$GFP)
a <- subset(data_ahl, Plasmid == receiver)
plot_atc <- ggplot(a, aes(x = GFP)) +
geom_density(color = 'green') +
ggtitle(label = c(receiver, "induced with aTC")) +
xlab("GFP") +
ylab("Density") +
theme_minimal() +
scale_x_continuous(limits = c(0,upperbound))
b <- subset(data_none, Plasmid == receiver)
plot_none <- ggplot(b, aes(x = GFP)) +
geom_density(color = 'green') +
labs(title = c(receiver, "no induction")) +
xlab("GFP") +
ylab("Density") +
theme_minimal() +
scale_x_continuous(limits = c(0,upperbound))
plot_list_atc[[j]] <- plot_atc
plot_list_none[[j]] <- plot_none
j = j+1
}
#----PLOTTING-----
grid.newpage()
main.vp <- viewport(layout = grid.layout(11,2))
pushViewport(main.vp)
pdf("receiver_plots.pdf", paper = "a4")
nplots <- length(plot_list_atc)
row = 1
for (i in 1:nplots){
print(plot_list_none[[i]], vp = viewport(layout.pos.row = row,
layout.pos.col = 1))
print(plot_list_atc[[i]], vp = viewport(layout.pos.row = row,
layout.pos.col = 2))
row = row + 1
}
dev.off()
3 回答
您必须先打开pdf设备,然后布局网格:
也许你可以试试multiplot我正在使用的功能 .
p1到p5是我的ggplot对象,在一列中对齐
谢谢大家回答,我设法最终解决了我的问题 . 显然,在声明视口之前必须打开pdf设备 . 我还设法以4乘2格的形式制作了地块 .
我包含代码以防有人发现它有用 .