Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reorder bars in geom_bar ggplot2 by value

Tags:

r

ggplot2

People also ask

How do I rearrange bars in ggplot2?

Reordering in ggplot is done using theme() function. Within this, we use axis. text. x with the appropriate value to re-order accordingly.

How do I reorder bars in R?

To reorder the bar graph in descending or ascending order, use the function reorder( ). There is no need to rename the data frame.

How do I change the order of bars in a bar graph?

Under Chart Tools, on the Design tab, in the Data group, click Select Data. In the Select Data Source dialog box, in the Legend Entries (Series) box, click the data series that you want to change the order of. Click the Move Up or Move Down arrows to move the data series to the position that you want.

What is the difference between Geom_col and Geom_bar?

geom_bar() makes the height of the bar proportional to the number of cases in each group (or if the weight aesthetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use geom_col() instead.


Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

Aside from what @Jaap answered, there are two other ways to order the plot:

1: By using desc argument for value:

ggplot(corr.m, aes(x = reorder(miRNA, desc(value)), y = value, fill = variable)) + 
   geom_bar(stat = "identity")

2: By releveling the miRNA factor and omitting reorder argument:

corr.m %>%
   arrange(desc(value)) %>%
   mutate(miRNA = factor(miRNA, levels = unique(miRNA))) %>% 
ggplot(aes(x = miRNA, y = value, fill = variable)) + 
   geom_bar(stat = "identity")