1

When I have the data named 'summarized',

enter image description here

if I make a bar graph using the below code

ggplot (data=summarized , aes(x=Stage, y=mean, fill=heat)) + 
  geom_bar(stat="identity",position="dodge", width = 0.5) + 
  geom_errorbar(aes(ymin= mean-se, ymax=mean + se), position=position_dodge(0.5) ,width=0.2) +
  scale_fill_manual(values= c ("darkslategray","azure3"), name="Treatment")

The graph is like this, but I want Pre-Anthesis to comes first. How can I change this order?

Many thansk,

enter image description here

Jin.w.Kim
  • 599
  • 1
  • 4
  • 15

1 Answers1

2

Try this:

library(dplyr)
library(ggplot2)
#Code
summarized %>%
  mutate(Stage=factor(Stage,levels = c('Pre-Anthesis','Post-Anthesis'),ordered = T)) %>%
  ggplot(aes(x=Stage, y=mean, fill=heat)) + 
  geom_bar(stat="identity",position="dodge", width = 0.5) + 
  geom_errorbar(aes(ymin= mean-se, ymax=mean + se), position=position_dodge(0.5) ,width=0.2) +
  scale_fill_manual(values= c ("darkslategray","azure3"), name="Treatment")

You can also try directly in ggplot2 function scale_x_discrete():

#Code2
ggplot (data=summarized , aes(x=Stage, y=mean, fill=heat)) + 
  geom_bar(stat="identity",position="dodge", width = 0.5) + 
  geom_errorbar(aes(ymin= mean-se, ymax=mean + se), position=position_dodge(0.5) ,width=0.2) +
  scale_fill_manual(values= c ("darkslategray","azure3"), name="Treatment")+
  scale_x_discrete(limits=c('Pre-Anthesis','Post-Anthesis'))

Output(in both cases):

enter image description here

Duck
  • 39,058
  • 13
  • 42
  • 84
  • 1
    Thank you so much, Duck. Your code totally works!!! Thanks a lot!!! – Jin.w.Kim Nov 19 '20 at 16:49
  • 1
    You can also use `fct_relevel` from the `forcats` package to reorder the factor levels in the `State` variable. Something like `mutate(State = fct_relevel(State, c("Pre-Anthesis", "Post-Anthesis")` – Eric Nov 19 '20 at 17:02