[英]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
箱线图,显示每个System
Score
方差,按中位数Score
排序。
ggplot(
muhData,
aes(
x=reorder(System, -Score, FUN=median),
y=Score
)
) + geom_boxplot()
I want to do the same for 10 other variables. 我想对其他10个变量执行相同的操作。 I tried just putting the column names in an array (
arrayOfColumnNames <- c(Score, Size, Temperature)
), but that didn't work. 我只是尝试将列名放在一个数组中(
arrayOfColumnNames <- c(Score, Size, Temperature)
),但这没有用。
I'm looking for a bunch of separate boxplots, not a lot of boxplots on one ggplot. 我正在寻找一堆单独的箱线图,而不是一个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. 该解决方案基于
get
功能。 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.
如果存在,它将给出此变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.