In this tutorial, we will learn how to arrange months in right order – chronologiocal order. By default, when we make a plot with months on one of the axis using ggplot2, we might get a plot with months ordered in alphabetical order, depending on how the month variable is stored in the data. Here we will learn how to use month as factor variable with levels in the right chronological order to have the plot with months in the right order.
library(tidyverse) theme_set(theme_bw(16))
Let us create a data frame with months as one variable and stock return as another variable. Note that the month variable in the example is a character variable.
year <- c("2024") set.seed(12345) df <- expand_grid(year, months=month.abb) |> mutate(returns= rnorm(n=12,mean=15,sd=20)) |> mutate(up_down=ifelse(returns>0, "+ve", "-ve"))
df # A tibble: 12 × 4 year months returns up_down <chr> <chr> <dbl> <chr> 1 2024 Jan 26.7 +ve 2 2024 Feb 29.2 +ve 3 2024 Mar 12.8 +ve 4 2024 Apr 5.93 +ve 5 2024 May 27.1 +ve 6 2024 Jun -21.4 -ve 7 2024 Jul 27.6 +ve 8 2024 Aug 9.48 +ve 9 2024 Sep 9.32 +ve 10 2024 Oct -3.39 -ve 11 2024 Nov 12.7 +ve 12 2024 Dec 51.3 +ve
When we make a barplot with months on x-axis and returns on y-axis, we get a barplot with months on x-axis ordered alphabetically.
df |> ggplot(aes(x=months, y=returns, fill=up_down))+ geom_col()+ theme(legend.position="bottom")+ labs(title="How to arrange months chronologically with ggplot2") ggsave("How_to_arrange_months_in_right_order_ggplot2.png", width=9, height=6)
To reorder months in the right order, i.e. chronologically, we first convert the month variable as factor with levels in the right chronological order. Then we can make the barplot as before.
df |> mutate(months = factor(months, levels = month.abb)) |> ggplot(aes(x=months, y=returns, fill=up_down))+ geom_col()+ theme(legend.position="bottom")+ labs(title="Arrange months chronologically with ggplot2") ggsave("arrange_months_in_right_order_ggplot2.png", width=9, height=6)
Now we get the months ordered correctly as we wanted.
Leave a Reply