用于传递名称在R中的数据文件和列的函数

时间:2015-01-12 11:14:19

标签: r ggplot2 lattice

我想为不同的变量集运行ggplot。我正在尝试创建一个函数,它可以作为参数,数据,变量和它们的名称,我想稍后在图中标记。以下是我想要的一个例子。你能否建议一下传递这些论点并获得结果的正确方法是什么? 因为我收到以下错误
    unique.default(x,nmax = nmax)出错:   unique()仅适用于矢量

v1 <- rep(c(2,4,6,8,10), each = 6)  
v2 <- rep(1:3,10)  
v3 <-runif(30,0.01,0.3)
v4 <-runif(30,0.05,0.9)
combined_data <- data.frame(v1,v2,v3,v4)  
library(ggplot2)
library(gridExtra)
p1<-myplot(combined_data, v3,v2,v1,"alpha1","beta","gamma")
p2<-myplot(combined_data, v4,v2,v1,"alpha2","beta","gamma")
grid.arrange(p1,p2) 

#--------------------------------------------------------------------------
myplot<-function(data, xvar, yvar, legend, xlab="", ylab="", factor="") 
{
 p<-ggplot(data,aes(x=xvar,y=yvar))+
  stat_summary(fun.y=mean,geom="smooth",aes(color=as.factor(legend)),linetype=2)+
  labs(x="xlab", y = "ylab", color = "factor")+
  theme(panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(), 
      panel.background = element_blank(),
      axis.line = element_line(colour = "black")
      )
   return(p)
  }

1 个答案:

答案 0 :(得分:1)

aes_string是实现这一目标的最简单方法。但是,因为您还想将颜色变量设置为factor,所以还需要使用paste0("factor(", legend, ")")构造。这是完整的代码。

myplot<-function(data, xvar, yvar, legend, xlab="", ylab="", factor="") 
{
  p<-ggplot(data, aes_string(x=xvar,y=yvar))+
    stat_summary(fun.y=mean, geom="smooth", 
                 aes_string(color=paste0("factor(", legend, ")")), 
                 linetype=2) +
    labs(x=xlab, y = ylab, color = factor)+
    theme(panel.grid.major = element_blank(),
          panel.grid.minor = element_blank(), 
          panel.background = element_blank(),
          axis.line = element_line(colour = "black")
    )
  return(p)
}
## --------------------------------------------------------------------------
p1 <- myplot(combined_data, "v3", "v2", "v1", "alpha1", "beta", "gamma")
p2 <- myplot(combined_data, "v4", "v2", "v1", "alpha2", "beta", "gamma")
grid.arrange(p1,p2)