Steph
Steph

Reputation: 3

R ggplot daily time series divided into months with several years

my data is a daily timeseries from 2010 to 2019 for sales.

I would like to have an line chart in one plot with all daily sales (1-30) for January for all years. And then a next Plot for February and so on. I painted a picture to better understand my problem.

If I'm using the facet_wrap or facet_grid function it's only for month perspective. I also tried the forecast::ggseansonplot() with an daily frequency but the output message is, that there is no seasonality. But i just want to have a plot and no analysis.

Illustration: Example image

library(ggplot2)
library(plyr)
library(readxl)

s <- read_excel("sales.xlsx")

s$date <- as.Date(s$date)
s$month <- as.Date(cut(s$date, breaks="month"))

base <- ggplot(s, aes(date, sales)) +
geom_line()
base + facet_wrap(~month, ncol=6)

Thanks for your help

Steph

Upvotes: 0

Views: 795

Answers (1)

Igor F.
Igor F.

Reputation: 2699

I suggest using lubridate, dividing your dates into days, months, and years, and then plotting them with the day on the x-axis and month as facet:

library(lubridate)
library(tidyverse)
set.seed(0)
s = tibble(
  date=ymd(20130101) + seq(1:(3*365)),
  sales = rnorm(3*365),
  day = day(date),
  month = month(date),
  year = as.factor(year(date))
)

ggplot(s, aes(day, sales, colour=year)) +
  geom_line() +
  facet_wrap(~month, ncol=6)

enter image description here

Upvotes: 1

Related Questions