0

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?

arezaie
  • 309
  • 2
  • 13
  • 1
    consider using `mixedsort` from gtools https://stackoverflow.com/questions/20396582/order-a-mixed-vector-numbers-with-letters – Pierre L Nov 10 '17 at 13:02

3 Answers3

4

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

Michael Harper
  • 14,721
  • 2
  • 60
  • 84
2

The order of the plotting is determined by how the levels of your factor are arranged. By default, this is done by alphabetical order. There a few ways of doing, but without knowing more about your data you can do:

ggplot(melted, aes(x = factor(c, levels=c("C_2", "C_4", "C_8", "C_16")), y = value)) + 
  geom_bar(stat="identity", width = 0.3) + 
  geom_hline(yintercept  = 33)
fmic_
  • 2,281
  • 16
  • 23
0

Well I did a quick and dirty method to solving this by using the following code

ggplot(melted,], aes(x = c, y = value)) + 
geom_bar(stat="identity", width = 0.3) + 
geom_hline(yintercept  = scale_reflist$reference_score[i]) + 
scale_x_discrete(limits=melted$c)

by sorting them in the last statement. Don't know if this is an "ok" method. Any feedback is appriciated

arezaie
  • 309
  • 2
  • 13