分组后如何在ggplot2中重新排序组?

时间:2018-07-12 13:12:09

标签: r ggplot2 grouping

我有这个data.frame:

classNr       geneName geneOrder
1        1 WBGene00017133        12
2        3 WBGene00002273         2
3        3 WBGene00015389        38
4        4 WBGene00016009         7
5        4 WBGene00009813        13
6        4 WBGene00000510        22
7        1 WBGene00001127         3
8        4 WBGene00015767        33
9        6 WBGene00007837        37
10       2 WBGene00004111        32
11       3 WBGene00015389        38
12       4 WBGene00018031        16
13       1 WBGene00006981        24
14       4 WBGene00007506        47
15       2 WBGene00015976        48
16       4 WBGene00006981        24
17       4 WBGene00001127         3
18       3 WBGene00003827        40
19       4 WBGene00000510        22
20       6 WBGene00007348        30

我得到以下情节:

ggplot(data=genesPerClassDF,aes(x=geneName, group=classNr, fill=classNr, order = geneOrder)) + 
      geom_density(adjust=0.3, position="fill") +
      theme(axis.text.x  = element_text(angle=90, vjust=0.5, size=12))+
      ylab("Class percentage")

enter image description here

如您所见,分组后按字母数字顺序对分组进行排序。如何更改(X轴的)顺序?

1 个答案:

答案 0 :(得分:1)

如果您要使其与数据中的顺序保持一致,则可以创建一个rowid列,然后通过它创建reorder x参数:

genesPerClassDF <- genesPerClassDF %>% 
  rowid_to_column()

ggplot(data=genesPerClassDF,aes(x=reorder(geneName, rowid), group=classNr, fill=classNr, order = geneOrder)) + 
  geom_density(adjust=0.3, position="fill") +
  theme(axis.text.x  = element_text(angle=90, vjust=0.5, size=12)) +
  xlab("geneName") +
  ylab("Class percentage")