Reordering in ggplot is done using theme() function. Within this, we use axis. text. x with the appropriate value to re-order accordingly.
To reorder the bar graph in descending or ascending order, use the function reorder( ). There is no need to rename the data frame.
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.
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:
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With