使用ggplot()的动态输入变量

时间:2015-04-03 18:51:24

标签: r dynamic plot ggplot2

我正在尝试避免复制粘贴代码,为此我需要使用ggplot()创建动态图。但是,很难开始工作。我让它与lm()部分一起使用(参见previous question here),然而,ggplot()给了我麻烦。我尝试了各种解决方案(见代码)。我发现了一个有效而又愚蠢的解决方案。任何人都有更好的解决方案来使用动态变量ggplot()

#Some test data
test = data.frame(gender=c(rep("Male",5),rep("Female",5)),
                  WM=round(rnorm(10)*100),
                  brain.g = round(rnorm(10)*100))

#plot function
plot.gender.scatter = function(data, dep.var, ind.var, gender.var) {
  #check types
  if (!is.character(dep.var) | !is.character(ind.var) | !is.character(gender.var)) {
    return("Input vars must be as strings.")
  }
  if (!is.data.frame(data)) {
    return("Data must be a data.frame.")
  }
  #models 
  model = lm(get(dep.var) ~ get(ind.var), data) #common model
  model.M = lm(get(dep.var) ~ get(ind.var), subset(data, get(gender.var)=="Male")) #male
  model.F = lm(get(dep.var) ~ get(ind.var), subset(data, get(gender.var)=="Female")) #female
  #plot it
  #ggplot(data, aes(x=ind.var, y=dep.var, color=gender.var)) +
  #ggplot(data, aes(x=data[ind.var], y=data[dep.var], color=data[gender.var])) +  
  #ggplot(data, aes(x=get(ind.var), y=get(dep.var), color=get(gender.var)) + 
  #ggplot(data, aes(x=get(data[ind.var]), y=get(data[dep.var]), color=get(data[gender.var]))) + 
  #ggplot(data, aes(x=eval(parse(text=ind.var)), y=eval(parse(text=dep.var)), color=eval(parse(text=gender.var)))) + 
  string = paste0("ggplot(data, aes(x=",ind.var,", y=", dep.var, ", color=",gender.var,")) + geom_point()")
  print(string)
  eval(parse(text=string))
}

plot.gender.scatter(test, "WM", "brain.g", "gender")

0 个答案:

没有答案