Home > Software design >  Order x-axis numerically ggplot2
Order x-axis numerically ggplot2

Time:07-13

I have the following dataframe (df):

# A tibble: 6 × 2
  chromosome     n
  <chr>      <int>
1 TcChr34-S     16
2 TcChr41-S     10
3 TcChr28-S      9
4 TcChr11-S      2
5 TcChr2-S       1
6 TcChr5-S       1

I want to make a barplot using ggplot2:

ggplot(data = df, 
       aes(y=n, 
           x=chromosome))   
  geom_bar(stat = "identity")

enter image description here

However, the x-axis labels are not generated in numerical order. How can I fix it, i.e., put it in the following order?

"TcChr2-S", "TcChr5-S", "TcChr11-S", "TcChr28-S", "TcChr34-S", "TcChr41-S"

CodePudding user response:

To order in ascending order of the numbers of chromosome, we have to pick out the numbers out of the string. This could be done with readrs parse_number() function (by the way up to this time my favorite function). The whole process is wrapped into to ´forcats´ ´fct_reorder´ function:

library(tidyverse)
df %>%
  ggplot(aes(y=n, x=fct_reorder(chromosome, parse_number(chromosome))))   
  geom_bar(stat = "identity")

enter image description here

  • Related