简体   繁体   中英

How do I loop through variables to make a bunch of ggplot2 boxplots while using the library's reorder() function?

I use this code to make a ggplot boxplot showing Score variance for each System , ordered by median Score .

ggplot(
  muhData, 
  aes(
    x=reorder(System, -Score, FUN=median), 
    y=Score
  )
) + geom_boxplot()

I want to do the same for 10 other variables. I tried just putting the column names in an array ( arrayOfColumnNames <- c(Score, Size, Temperature) ), but that didn't work.

I'm looking for a bunch of separate boxplots, not a lot of boxplots on one ggplot.

What do I do?

I am not sure if I correctly understood what you want but take a look at this:

library(ggplot2)
#toy data
system<-sample(c("a","b","c"),100, replace=TRUE)
var1<-rnorm(100)
var2<-rnorm(100)
var3<-rnorm(100)
data<-data.frame(system,var1,var2,var3)

plot_list<-list()
for (i in 1:3){     
#save plots as single objects
assign(paste0("plot",i),ggplot()+geom_boxplot(aes(x=reorder(system,get(names(data)[i+1])),y=get(names(data)[i+1])))) 
#or all together in a list
plot_list[[i]]<-ggplot()+geom_boxplot(aes(x=reorder(system,get(names(data)[i+1]),median),y=get(names(data)[i+1])))
}

The solution is based on the get funtion. It takes a character string as input and looks if there is a variable with the same name. If there is, it gives this variable.

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