[英]Extract plots from function and plot as one item
我有一个函数可以生成一个图,该图可以运行六次。 我想提取每个图,然后用每个图和一个图例绘制一个多面板图。
我已经尝试使用assign函数以及return来提取我的图,但是我似乎无法使其正常工作。
我的代码:
levels = c('Genus','Family','Order','Class','Phylum','Domain')
Taxon_senPrec_func = function(x){
df = subset(d, Taxonomic_level == x)
q=ggplot(df, aes(x=Sensitivity, y=Precision, col=Database, shape=ID_cutoff)) +
geom_point(size=3) +
ggtitle(
paste('The ',x,' sensitivity and precision of various annotation techniques.',
sep='')) +
ylim(0,100) +
xlab('Sensitivity (%)') +
ylab('Precision (%)') +
scale_shape_manual(values=1:9)
p = assign(paste("plot_",x,sep=""), q)
return(p)
}
for(level in levels){
Taxon_senPrec_func(level)
}
为了扩展facet_grid
注释,我们尝试使用自定义函数基于一个data.frame
子集分别绘制多个图,然后尝试将它们放到一个图中,为什么不使用facet_grid。
例:
require(ggplot2)
#reproducible dummy data
set.seed(123)
df <- data.frame(Sensitivity=runif(600,1,100),
Precision=runif(600,1,100),
Database=sample(c("DB1","DB2","DB3"),600,replace = TRUE),
ID_cutoff=sample(LETTERS[1:4],600,replace = TRUE),
my_levels = c('Genus','Family','Order','Class','Phylum','Domain'))
#plot with facet
ggplot(df, aes(x=Sensitivity, y=Precision, col=Database, shape=ID_cutoff)) +
geom_point(size=3) +
facet_grid(.~my_levels) +
ggtitle('The sensitivity and precision of various annotation techniques.') +
ylim(0,100) +
xlab('Sensitivity (%)') +
ylab('Precision (%)') +
scale_shape_manual(values=1:9)
情节:
一种方法是使用multiplot函数(从此处开始 ),如下所示:
multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
require(grid)
plots <- c(list(...), plotlist)
numPlots = length(plots)
if (is.null(layout)) {
layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
ncol = cols, nrow = ceiling(numPlots/cols))
}
if (numPlots==1) {
print(plots[[1]])
} else {
grid.newpage()
pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))
for (i in 1:numPlots) {
matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))
print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
layout.pos.col = matchidx$col))
}
}
}
并可以像这样使用它:
library(ggplot2);
library(grid)
q1<-ggplot(...) #your first graph
q2<-ggplot(...) # your second graph
...
q6<-ggplot(...) # 6-th graph
然后调用multiplot(q1,q2,q3,q4,q5,q6,cols=3)
。 有各种替代方法:看这里 ,它使用grid.arrange
,还有当然是用附带的小类型ggplot
: facet_grid
(如巴蒂斯特说)和facet_wrap
,后者可以是这样的(随机/伪使用数据):
times_<-c(0,cumsum(rexp(19,1)));
out.df<-matrix(c(sample(-10:10,20,TRUE),sample(-10:10,20,TRUE),sample(-10:10,20,TRUE),
sample(-10:10,20,TRUE),rep(times_,4),c(rep(1,20),rep(2,20),rep(3,20),rep(4,20))), ncol=3);
out.df<-as.data.frame(out.df); colnames(out.df)<-c("R","time","qq");
ggplot(out.df,aes(x=time, y=R) )+geom_line(colour='blue')+
facet_wrap(~ qq, ncol = 2, scales="free")
这给出了一个奇妙的情节:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.