Search code examples
rdataframeggplot2visualizationgeom-bar

Need to adjust ordering of subgroups on geom_bar plot


Need some help trying to order the individual bars on this plot so that they are in the same order in both the "Pre-innoculation" and "Post-innoculation" category. I have tried manually setting the levels for the disease.state vector in both the ggplot code and the line creating the dataframe itself. Not sure why I'm having such trouble with this. Thank you greatly!

df.graph1 <- data.frame(
  exp.period = factor(c("Pre-innoculation", "Pre-innoculation", "Pre-innoculation", "Post-innoculation", "Post-innoculation", "Post-innoculation"), levels=c("Pre-innoculation", "Post-innoculation")),
  disease.state = factor(c("Apparent", "Possible", "NA", "Apparent", "Possible", "NA"), levels = c("NA", "Possible", "Apparent")),
  count = factor(c(3, 12, 15, 11, 18, 9),))

ggplot(df.graph1, aes(x=factor(exp.period, level=c('Pre-innoculation', 'Post-innoculation')), y=count, fill=disease.state)) + 
  geom_bar(stat="identity", position=position_dodge(), colour="black") + 
  theme_classic() + 
  xlab("Experimental Period") + 
  ylab("") +
  guides(fill=guide_legend(title="Disease State"))

Solution

  • 
    df.graph1$disease.state=factor(df.graph1$disease.state,levels = c("NA","Possible","Apparent"),ordered = T) #set order of bars
    
    df.graph1$observations=as.numeric(as.character(df.graph1$count)) #convert count to numeric (try what happens, if you only convert to numeric, without converting to character first)
    
    ggplot(df.graph1, aes(x=exp.period, y=observations,
                          fill=disease.state)) + 
      geom_col(position=position_dodge(), colour="black") + 
      theme_classic() + 
      xlab("Experimental Period") + 
      ylab("") +
      guides(fill=guide_legend(title="Disease State"))