0

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:

enter image description here

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: enter image description here

Any suggestion is appreciated. Thank you for your time!

agenis
  • 8,069
  • 5
  • 53
  • 102
aleia
  • 59
  • 5
  • Possibly usefull: [Reorder bars in geom_bar ggplot2](http://stackoverflow.com/questions/25664007/reorder-bars-in-geom-bar-ggplot2/25664367#25664367) – Jaap Jun 30 '16 at 15:29
  • I don't think the code works because I have 3 conditions not 1 – aleia Jun 30 '16 at 15:36
  • See this question and answer too: http://stackoverflow.com/q/29221824/3871924 – agenis Jun 30 '16 at 15:39

2 Answers2

2

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")

enter image description here

Note: Can't reproduce your graph because you didn't set a seed for the random sampling.

Community
  • 1
  • 1
Psidom
  • 209,562
  • 33
  • 339
  • 356
0

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)
agenis
  • 8,069
  • 5
  • 53
  • 102