Search code examples
rplotggplot2bar-chartr-factor

Reordering ggplot2 barplots by a mixed character and numerical variable


I am making a barplot within ggplot which looks like this:

barplot

and this is my code:

ggplot(melted, aes(x = c, y = value)) + 
   geom_bar(stat="identity", width = 0.3) + 
   geom_hline(yintercept  = 33)

my data looks like the following:

  c        variable    value
  C_2      qd          55.29899
  C_4      qd          55.00241
  C_8      qd          54.43281
  C_16     qd          53.37958

How can I reorder the bars so that they show in "numeric order" of C_2, C_4, C_8, C_16?


Solution

  • When you have text in R, it will normally be converted it into a factor. By default, this factor is ordered alphabetically:

    > melted$c
    [1] C_2  C_4  C_8  C_16
    Levels: C_16 C_2 C_4 C_8
    

    ggplot will use the order of the factor when plotting the graph. You can use the factor function to manually specify the order or the levels:

    melted$c <- factor(melted$c, levels=c("C_2", "C_4", "C_8", "C_16"))
    

    In this case, manually setting the order isn't too difficult. Alternatively this could be done automatically using the mixedsort function from the gtools package:

    library(gtools)
    melted$c <- factor(melted$c, levels=mixedsort(as.character(melted$c)))
    

    Using your original code:

    ggplot(melted, aes(x = c, y = value)) + 
      geom_bar(stat="identity", width = 0.3) + 
      geom_hline(yintercept  = 33)
    

    enter image description here