tr3quart1sta
tr3quart1sta

Reputation: 169

How to reorder groups in ggplot2 after grouping?

I have this 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

and I get the following plot:

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

As you can see after grouping the groups are ordered alphanumerically. How can I change this order (of the X axis)?

Upvotes: 0

Views: 858

Answers (1)

Paul Campbell
Paul Campbell

Reputation: 876

If you want to keep them in the same order as in the data you can create an rowid column then reorder the x argument by it:

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")

Upvotes: 1

Related Questions