简体   繁体   中英

how to use aes_string for groups in ggplot2 inside a function when making boxplot

new to ggplot2, I've scoured the web but still couldn't figure this out. I understand how to plot a boxplot in ggplot2, my problem is that I can't pass along the variable I use for groups when it is inside a function.

so, normally (ie NOT inside a function), I would write this:

ggplot(myData, aes(factor(Variable1), Variable2)) +
    geom_boxplot(fill="grey", colour="black")+
    labs(title = "Variable1 vs. Variable2" ) +
    labs (x = "variable1", y = "Variable2")

Where myData is my data frame Variable 1 is a 2 level factor variable Variable 2 is a continuous variable I want to make boxplots of Variable 1 by its 2 levels/groups and this works fine, but as soon as I write this inside a function I couldn't get it to work.

my attempt in writing the function:

myfunction = function (data, Variable1) {
    ggplot(data=myData, aes_string(factor("Variable1"), "Variable2"))+
    geom_boxplot(fill="grey", colour="black")+
    labs(title = paste("Variable1 vs. Variable2" )) +
    labs (x = "variable1", y = "Variable2")
}

this only gives me a single boxplot(instead of 2), as if it never understood the factor(Variable1) command (and did a single boxplot of the entire Variable 2, rather than separate them by Variable 1 level first, then boxplot them).

Aes_string evaluates the entire string, so if you do sprintf("factor(%s)",Variable1) you get the desired result. As a further remark: your function has a data-argument, but inside the plotting you use myData . I have also edited the x-lab and title, so that you can pass 'Variable3' and get proper labels.

With some example data:

set.seed(123)
dat <- data.frame(Variable2=rnorm(100),Variable1=c(0,1),Variable3=sample(0:1,100,T))

myfunction = function (data, Variable1) {
  ggplot(data=data, aes_string(sprintf("factor(%s)",Variable1), "Variable2"))+
    geom_boxplot(fill="grey", colour="black")+
    labs(title = sprintf("%s and Variable2", Variable1)) +
    labs (x = Variable1, y = "Variable2")
}

p1 <- myfunction(dat,"Variable1")
p2 <- myfunction(dat,"Variable3")

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM