[英]R: How are factor labels mapped to the correct values in a data.frame?
[英]How to rank values in a data.frame for each factor in R
我有一个看起来像这样的数据集:
Subject <- rep(1:5, each = 3)
Condition <- rep(-1:1,5)
DV <- rnorm(15)
foo <- cbind(Subject,Condition,DV)
foo <- data.frame(foo)
foo <- within(foo, {
Subject <- factor(Subject) #I'm converting subject to factor because that's how it is in my actual dataset
Condition <- factor(Condition)
})
这就是我的图的样子:
我想做的是重新组织数据,以便首先绘制条件-1最大值的对象,然后绘制第二个最大值的对象,依此类推。 我希望我的图看起来像这样:
任何建议表示赞赏。 感谢您的时间!
使用@Procrastinatus的答案中的reorder
功能,您可以执行以下操作:
ggplot(foo, aes(x = reorder(Subject, -rep(DV[Condition == -1], each = 3)),
y = DV, fill = Condition)) +
geom_bar(stat = "identity", position = "dodge") +
xlab("subject")
注意:由于您没有为随机抽样设置种子,因此无法重现图形。
要以自定义的方式对条形进行重新排序,ggplot的scale_x_discrete
参数的使用非常简单。
我首先用dplyr
计算了正确的顺序,但是其他任何方法都可以。
library(dplyr)
myorder <- foo %>% filter(Condition==-1) %>% arrange(desc(DV)) %>% .$Subject
ggplot(data=foo) +
aes(x=Subject, y=DV, fill=Condition) +
geom_bar(stat="identity", position="dodge") +
scale_x_discrete(limits=myorder)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.