Hi everyone,
I need to build a barplot showing the sold qty of three different services on a weekly basis. I need to add as x-axis label either the calendar week and the month.
See the image for an example:
Here is my code:
sample <- data.frame(service_type = c("A","B","C","A","B","C","A","B","C","A","B","C","A","B","C","A","B","C","A","B","C"),
qty = c(38,185,87,29,12,133,2,14,31,2,9,59,60,43,137,135,31,159,15,32,1),
year_week = c("2022 - CW02","2022 - CW02","2022 - CW02","2022 - CW03","2022 - CW03","2022 - CW03","2022 - CW04","2022 - CW04","2022 - CW04","2022 - CW05","2022 - CW05","2022 - CW05","2022 - CW06","2022 - CW06","2022 - CW06","2022 - CW07","2022 - CW07","2022 - CW07","2022 - CW08","2022 - CW08","2022 - CW08"),
xlabel2 = c("Jan-22","Jan-22","Jan-22","Jan-22","Jan-22","Jan-22","Jan-22","Jan-22","Jan-22","Feb-22","Feb-22","Feb-22","Feb-22","Feb-22","Feb-22","Feb-22","Feb-22","Feb-22","Feb-22","Feb-22","Feb-22")
)
## To use annotate
sample %>%
#arrange(desc(dat_cal_week_id)) %>%
ggplot() +
aes(x = year_week, fill = service_type, weight = qty) +
geom_bar(position = "dodge") +
scale_fill_hue(direction = 1) +
theme_minimal() +
#theme(legend.position = "left", axis.text.x = element_text(angle=90, hjust=1)) +
theme(legend.position = "left", axis.text.x = element_blank()) +
coord_cartesian(clip = "off") +
annotate(geom = "text",
x = 1:(nrow(sample)/3),
y = min(sample$qty),
label = unique(sample$xlabel2),
vjust = 1,
angle = 90)
## Using facet_wrap
sample %>%
#arrange(desc(dat_cal_week_id)) %>%
ggplot() +
aes(x = year_week, fill = service_type, weight = qty) +
geom_bar(position = "dodge") +
scale_fill_hue(direction = 1) +
theme_minimal() +
theme(legend.position = "left", axis.text.x = element_text(angle=90, hjust=1)) +
facet_wrap(sample$xlabel2, strip.position = "bottom")+
theme(strip.placement = "outside")
The first try is with annotate but I receive the error 'Error in annotate()
:
! Unequal parameter lengths: x (7), label (2)'
The second try is with facet_wrap and I receive another error 'Error in eval_tidy(facet, mask) : object 'Jan' not found'
I'm not sure that any of these approaches are correct.
I really appreciate anyone who can help me with this.
Thanks