[英]How to create a function with a for loop to obtain multiple pdf files (unique per id) with ggplots on spearate pages
我正在嘗試使用 function 和 for 循環創建 pdf 報告文件,但我想在我的文件中每頁有 1 個 ggplot。 我創建了這個 function 和 for 循環,以便每個名稱能夠有 1 個報告,因為它需要個性化。 到目前為止,我的代碼看起來像這樣
tv<- data.frame(
name = c("p1","p2","p3","p1","p2","p3","p1","p2","p3","p1","p2","p3", "p1", "p2", "p3", "p1", "p2", "p3", "p1", "p2", "p3", "p1", "p2", "p3", "p1", "p2", "p3"),
dates = c("2010", "2010", "2010", "2010", "2010", "2010", "2010", "2010", "2010","2011", "2011", "2011", "2011", "2011", "2011", "2011", "2011", "2011", "2015", "2015", "2015", "2015", "2015", "2015", "2015", "2015", "2015" ),
results = c(40, 40, 45, 50, 52, 52, 53, 54, 56, 70, 50, 10, 40, 55, 55, 60, 60, 70, 30, 60, 60, 55, 55, 54, 32, 33, 57),
parameter = c("D", "D", "D", "R", "R", "R", "C", "C", "C", "D", "D", "D", "R", "R", "R", "C", "C", "C","D", "D", "D", "R", "R", "R", "C", "C", "C")
)
ftv <- function(id){
Ttv <- tv %>% filter(name == id)
ggplot(Ttv, aes(dates, results, group = parameter)) +
geom_point() +
geom_line() +
theme(axis.text.x = element_text(size= 6, angle = 90), strip.text = element_text(size = 6))+
facet_wrap(~parameter, scales = "free")+
ggsave(paste0("~/Desktop//", id, "_test.pdf"))
}
for(id in unique(tv$name)){
ftv(id)
}
我得到了這個
我想擁有相同類型的文件,但每個頁面包含 1 個 plot,考慮到稍后我可能希望文件中包含 3 個以上的圖形。
謝謝你的幫助。
這是你想要的嗎?
# create a new variable that combines the two variables for identifying cases
tv$name_parameter<-paste0(tv$name,tv$parameter)
ftv <- function(id){
Ttv <- tv %>% filter(name_parameter == id) # use the new identifier here
ggplot(Ttv, aes(dates, results, group = parameter)) +
geom_point() +
geom_line() +
theme(axis.text.x = element_text(size= 6, angle = 90), strip.text = element_text(size = 6))+
# # remove facet_wrap bc you're using `parameter` to paginate
# facet_wrap(~parameter, scales = "free")+
ggsave(paste0("~/Desktop//", id, "_test.pdf"))
}
for(id in unique(tv$name_parameter)){ # again, the new identifier
ftv(id)
}
嘗試這個:
#Function
ftv <- function(id){
Ttv <- tv %>% filter(name == id)
LTtv <- split(Ttv,Ttv$parameter)
Lplot <- lapply(LTtv, function(x)
ggplot(x, aes(dates, results, group = parameter)) +
geom_point() +
geom_line() +
theme(axis.text.x = element_text(size= 6, angle = 90), strip.text = element_text(size = 6))+
facet_wrap(~parameter, scales = "free"))
#Export
pdf(paste0(id,'.pdf'),width = 14)
lapply(Lplot,plot)
dev.off()
}
#Apply
for(id in unique(tv$name)){
ftv(id)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.