Andres Alvarado
Andres Alvarado

Reputation: 196

Reorder not working in ggplot with multiple facets

I have the data below:

   LETTER            ID NUMBER
1       A 805qhau1hbnm1  0.001
2       A 47s11wwxy8x7c  0.521
3       A 92g6022uvxtmf  0.036
4       A 92pkgg5y0gvkk  0.002
5       B gxx44abszy02j  0.066
6       B agupupsu0gq26  0.001
7       B 92g6022uvxtmf  0.003
8       B 92g6022uvxtmf  0.003
9       B agupupsu0gq26  0.004
10      B dwvprfgxafqct  0.058
11      B 92pkgg5y0gvkk  0.161
12      B 2264vrpp4b02v  0.444
13      B 92g6022uvxtmf  0.084
14      B 1ypga6ay26dyk  0.018
15      B 9tkrv34jdmvtk  0.414
16      B agupupsu0gq26  0.001
17      B agupupsu0gq26  0.002
18      B gxx44abszy02j  0.065
19      B 0mtz8hnvvm63r  0.012
20      B 9ta79k8xtyzdy  0.006
21      B 92g6022uvxtmf  0.014
22      A 47s11wwxy8x7c  0.539
23      A 92g6022uvxtmf  0.028
24      A 92pkgg5y0gvkk  0.003
25      A 92pkgg5y0gvkk  0.002
26      A 805qhau1hbnm1  0.001
27      A fmubqnkxnj16f  0.451
28      B 448pxv1p0ffjp  0.040
29      B 3cj2kj0rx311k  0.012
30      B 9ta79k8xtyzdy  0.006
31      B gxx44abszy02j  0.064
32      B agupupsu0gq26  0.002
33      B agupupsu0gq26  0.001
34      A 92pkgg5y0gvkk  0.002
35      A 65a353h1x9yfd  0.055
36      B dbrx980zu7bmk  0.009

And I have the ggplot code below:

l_myPlot <- ggplot(data=l_data, aes(x=reorder(x=ID, X=NUMBER, sum, order=T), y = NUMBER))+
  geom_bar(stat='identity' )+
  facet_wrap(~ LETTER, scales="free_x")+ 
  theme(axis.text.x=element_text(angle=90, hjust=1))+ 
  scale_y_continuous()

As you can see, I am reordering the x axis based on the addition of the number column. The issue is that the sorting is not being done properly. The A facet ID 92...vkk should be the second bar in the order, not the fourth.

enter image description here

Upvotes: 0

Views: 349

Answers (1)

Mist
Mist

Reputation: 1948

My approach is to use factors to order a new identifier created out of LETTER and ID and then use scale_x_discrete(labels =) to alter the x axis labels.

library(ggplot2)
library(dplyr)
# summarise the data
ld <- l_data %>% group_by(LETTER, ID) %>% transmute(sum = sum(NUMBER))
ld <- ld[!duplicated(ld) ,]
# Sort in correct order
ld <- ld[with(ld, order(LETTER, sum)) ,]
# Factor in the sorted order
ld$new_ID <- factor(paste(ld$LETTER, ld$ID), 
                    levels = paste(ld$LETTER, ld$ID))
# Plot
l_myPlot     <- ggplot() +
  geom_bar( data = ld,
            aes(x  = new_ID,
                y  = sum ),
            stat = 'identity' ) +
  facet_wrap( ~ LETTER
              , scales = "free_x"
  ) +
  scale_x_discrete(labels=ld$ID) +
  theme ( axis.text.x = element_text( angle = 90, hjust = 1 ) ) +
  scale_y_continuous()
l_myPlot

Upvotes: 3

Related Questions