重新排序不在gpplot中使用多个方面

时间:2015-12-16 00:21:13

标签: r ggplot2

我有以下数据:

   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

我有以下ggplot代码:

l_myPlot     <- ( ggplot( data       = l_data
                         , aes( x     = reorder( x = ID, X = NUMBER, sum, order = TRUE )
                              , 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()
                 )

如您所见,我正在根据添加数字列(第2行)重新排序x轴。问题是排序没有正确完成。请看一下 A 方面,ID 92...vkk应该是订单中的第二个栏,而不是第四个栏。

enter image description here

1 个答案:

答案 0 :(得分:3)

我的方法是使用因子来订购由LETTER和ID创建的新标识符,然后使用scale_x_discrete(labels =)来更改x轴标签。

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