Search code examples
rggplot2plotdplyrtime-series

How to use the function facet_wrap() to plot time series data in ggplot2 in R


Issue

I am doing a project which requires to use ggplot2 to plot time series data.

I've tried to plot the frequency of bulbs per year per month but the dimensions don't look accurate, the x-axis only denotes January, and header 'year'are larger than the bars, which you can hardly see.

Does anyone know how to modify the R-code to look more like the desired outcome?

Many thanks if you can help.

Example of my Data Frame

   year     month Number_Daffodils Frequency_New_Bulbs       date n_month
1  2012   January                1                   7 2012-01-01       1
2  2012  February                8                  59 2012-02-01       2
3  2012     April               18                 144 2012-04-01       4
4  2012       May               21                 193 2012-05-01       5

This is what I've done so far:

 #Note that %b represents the abbreviated month which will be plotted as labels on the x-axis.
 #Use the column 'date' that contains month of the year as a class of type date


Year_Group_Size<-dat_Ds %>% 
                            ggplot(aes(x = date, y = Frequency_New_Bulbs)) +
                            geom_bar(stat = "identity", fill = "darkorchid4") +
                            facet_wrap(~ year, ncol = 3) +
                            labs(title = "Montly Total Estimated Group Size Per Month Per Year",
                            subtitle = "Data plotted by year",
                            y = "Estimated Group Size",
                            x = "Month") + theme_bw(base_size = 15) +
                            scale_x_date(date_labels = "%b")

Dummy Dataframe

tibble(
  Month = sample(month.name, 120, replace = TRUE),
  Year = sample(2012:2024, 120, replace = TRUE),
  Date = Sys.Date(), 120, replace = TRUE,
  Number_Daffodils = sample(1:5, 120, replace = TRUE)
  ) 

Output

enter image description here

Desired Output
enter image description here


Solution

  • Summarise the data before plotting, try this example:

    library(ggplot2)
    library(dplyr)
    
    dat_Ds <- data.frame(
      Month = sample(month.name, 120, replace = TRUE),
      Year = sample(2012:2024, 120, replace = TRUE),
      Date = Sys.Date() + 1:120,
      Number_Daffodils = sample(1:5, 120, replace = TRUE)) 
    
    dat_Ds_sum <- dat_Ds %>% 
      mutate(myMonth = factor(substring(Month, 1, 3), month.abb)) %>% 
      group_by(Year, myMonth) %>% 
      summarise(mySum = sum(Number_Daffodils))
    
    ggplot(dat_Ds_sum, aes(x = myMonth, y = mySum)) +
      geom_bar(stat = "identity", fill = "darkorchid4") +
      facet_wrap(~ Year, ncol = 3)
    

    enter image description here