Reputation: 59
I have a dataset that looks something like this:
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)
})
And this is how my graph looks like:
What I would like to do is reorganize the data so that the subject with the largest value for condition -1 is plotted first, then second largest value plotted second and so on. I would like my graph to look like this:
Any suggestion is appreciated. Thank you for your time!
Upvotes: 0
Views: 459
Reputation: 8377
To reorder your bars in a customized way, the use of the scale_x_discrete
argument of ggplot is quite straightforward.
I first calculated the right order with dplyr
but any other way is fine.
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)
Upvotes: 0
Reputation: 215057
Use the reorder
function from @Procrastinatus's answer, you can do something like:
ggplot(foo, aes(x = reorder(Subject, -rep(DV[Condition == -1], each = 3)),
y = DV, fill = Condition)) +
geom_bar(stat = "identity", position = "dodge") +
xlab("subject")
Note: Can't reproduce your graph because you didn't set a seed for the random sampling.
Upvotes: 2