-1

I have a dataframe like this:enter image description here

> str(mydata6)
'data.frame':   6 obs. of  4 variables:
 $ Comparison            : Factor w/ 6 levels "Decreased_Adult",..: 5 2 6 3 4 1
 $ differential_IR_number: num  446 305 965 599 1799 ...
 $ Stage                 : Factor w/ 3 levels "AdultvsE11","E14vsE11",..: 2 2 3 3 1 1
 $ Change                : Factor w/ 2 levels "Decrease","Increase": 2 1 2 1 2 1

column 1,3,4 are factors and column 2 are numeric I used the following code to do a bargraph:

ggplot(mydata6, aes(x=Stage, y=differential_IR_number, fill=Change)) + #don't need to use "" for x= and y, comparing to the above code
  geom_bar(stat = "identity", position = "stack") + #using stack to make decrease and increase stack with each other
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) + #using theme function to change the labeling to be vertical
  geom_text(aes(label=differential_IR_number), position=position_stack(vjust=0.5))

The result is following: enter image description here

But I want the order to be E14vsE11 E18vsE11 and AdultvsE11, I tried to reorder/sort at different positions but none works.

Why it does not following the order of mydataframe?

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Kyle
  • 49
  • 7
  • As far as I can tell, your graphic follows your order of factors in column `Stage`. You could reorder `Stage`'s factor levels using package `forcats` and the `fct_reorder` function. – Martin Gal Jun 25 '20 at 23:14
  • I tried it by using reorder(Stage), the output looks the same though. – Kyle Jun 25 '20 at 23:23
  • Possible duplicate https://stackoverflow.com/questions/5208679/order-bars-in-ggplot2-bar-graph – Ronak Shah Jun 26 '20 at 00:14
  • I have reached that one. And tried sort on Stage. Not be able to get the result. Laurent's response below help better understanding the meaning of level for me. Thank you very much – Kyle Jun 26 '20 at 09:32

1 Answers1

1

The order is the one of the levels of the factor. You can set the order you want as follows:

mydata6$Stage <- factor(mydata6$Stage, levels = c("E14vsE11", "E18vsE11", "AdultvsE11"))
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225