Reputation: 1004
I have a df with a list of dates which I want to show in a bar chart by week of the year. I need for it to display in the form of YearWeek eg 202034 and if there aren't any for that week, the bar needs to show zero.
I can plot this using just the dates and the blanks are shown:
library(tidyverse)
library(lubridate)
set.seed(93)
df<-data.frame(date=sample(seq(as.Date('2020-08-01'), as.Date('2020-09-30'), by="day"), 5,replace=TRUE))
df$yearweek<-paste0(year(df$date),isoweek(df$date))
ggplot(data = df) +
geom_bar(
mapping = aes(x=`date`))
If I try to plot this using the year and week then any weeks where there is missing data, the bars aren't there.
How can I amend the code so it shows the blank weeks in the bar chart?
Upvotes: 0
Views: 73
Reputation: 2114
Something like this? Edited the answer to reflect comment.
library(tidyverse)
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#>
#> date, intersect, setdiff, union
set.seed(93)
df<-data.frame(date=sample(seq(as.Date('2020-08-01'), as.Date('2020-09-30'), by="day"), 5,replace=TRUE))
df$yearweek<-paste0(year(df$date),isoweek(df$date))
df <- df %>%
mutate(week_floor=lubridate::floor_date(date, unit = "week"))
ggplot(data = df) +
geom_bar(
mapping = aes(x=week_floor))+
scale_x_date(breaks=scales::date_breaks(width = "1 week"),
labels=scales::date_format(format="%Y%U"))
Created on 2020-12-10 by the reprex package (v0.3.0)
Upvotes: 1