Search code examples
rggplot2geom-barggplotlygeom-text

Months on x-axis instead of number


I'm want to convert the numbers in the x-axis into months and I succeeded somehow but I want months to arrange in chronological order instead of alphabetical order.

I used the following code:

temp %>% 
  ggplot(aes(month.abb[MoSold], fill = SalePrice)) + 
  geom_bar() +
  scale_y_continuous(labels = number) +
  xlab("Month") +
  theme_bw()

the above code is producing following graph months in alphabetical order.

Instead, I want the graph to look like with name instead of the number graph with chronological order without month name


Solution

  • month.abb[] produces characters, which don't have an inherent order to them in R aside from alphabetical, which is how ggplot displays them.

    ggplot(data = data.frame(
      months = month.abb[1:10],
      num = 1:10),
      aes(months, num)) +
      geom_col()
    

    enter image description here

    To see them in the expected order, there are at least 3 options:

    1. convert the month.abb to the factor data type, which can have a specified order.

      Convert months to factors using forcats package

      ggplot(data = data.frame( months = forcats::fct_reorder(month.abb[1:10], 1:10), num = 1:10), aes(months, num)) + geom_col()

      Convert months to factors using base R

      ggplot(data = data.frame( months = factor(1:10, labels = month.abb[1:10]), num = 1:10), aes(months, num)) + geom_col()

    enter image description here

    1. Or you might alternately use a numerical axis, with custom labels reflecting what you want:

      ggplot(data = data.frame( month_num = 1:10, num = 1:10), aes(month_num, num)) + geom_col() + scale_x_continuous(labels = function(x) month.abb[x])

    2. Or perhaps easiest of all, you might use a Date or POSIXct data type.

      ggplot(data = data.frame( month = seq.Date(as.Date("2019-01-01"), as.Date("2019-10-01"), by = "month"), num = 1:10), aes(month, num)) + geom_col() + scale_x_date(date_breaks = "1 month", minor_breaks = NULL, date_labels = "%b") enter image description here