Reputation: 2076
I want to generate a boxplot for all the variable in my data frame. But the problem is i cannot get the x axis to be labelled with the variable name which is looping via lapply. Any thoughts.
df=data.frame(a=rnorm(100), b=rnorm(100), c=rnorm(100), d=rep(1:2,50)) # data
df$d=as.factor(df$d)
Function for box plot
Boxplotfun=function(x,i){
if(is.numeric(x)) {
p <- ggplot(df, aes(d, x, group=d)) + geom_boxplot(outlier.colour = "red", fill = c("gold","darkgreen")) + coord_flip() + theme_light() + ggtitle(paste(names(x)))
plot(p)
}
}
l=lapply(df[-ncol(df)], Boxplotfun)
Upvotes: 1
Views: 187
Reputation: 680
Instead of using the dataframe as first argument to lapply, you can use the names of the dataframe directly and just refer to your dataframe inside of your plot function.
Instead of using aes, I have also used aes_string so that I can pass "x" inside and ggplot understands that I am not looking for variable x but rather for the variable whose name "x" refers to
Boxplotfun=function(x) {
if(is.numeric(df[, x])) {
p <- ggplot(df, aes_string("d", x, group="d")) +
geom_boxplot(outlier.colour = "red", fill = c("gold","darkgreen")) +
coord_flip() + theme_light() +
ggtitle(x)
plot(p)
}
}
ll <- lapply(names(df[-ncol(df)]), Boxplotfun)
Edit: If you want the legend to appear, you should, as Axeman's answer has shown, specify fill inside your aes and use scale_fill_manual to pick the colors:
Boxplotfun=function(x) {
if(is.numeric(df[, x])) {
p <- ggplot(df, aes_string("d", x, fill="d")) +
geom_boxplot(outlier.colour = "red")+
scale_fill_manual(values = c("gold","darkgreen")) +
coord_flip() + theme_light() +
ggtitle(x)
plot(p)
}
}
Upvotes: 1
Reputation: 35242
Just to make Richard's comment into an answer:
df <- data.frame(a=rnorm(100), b=rnorm(100), c=rnorm(100), d=rep(1:2,50)) # data
df$d <- as.factor(df$d)
df2 <- tidyr::gather(df, 'var', 'val', -d)
ggplot(df2, aes(d, val, fill = d)) +
geom_boxplot(outlier.colour = "red") +
scale_fill_manual(values = c("gold","darkgreen")) +
coord_flip() +
theme_light() +
facet_grid(var~.)
Upvotes: 2