我需要建立一个条形图,显示每周销售的三种不同服务的数量。我需要添加日历周和月份作为 x 轴标签。 示例见图片:
这是我的代码:
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")
第一次尝试使用 annotate 但我收到错误 'Error in
annotate()
:
!参数长度不等:x(7),label(2)'
第二次尝试是使用 facet_wrap,我收到另一个错误 'eval_tidy(facet, mask) 中的错误:找不到对象 'Jan''
我不确定这些方法是否正确。 我真的很感谢任何能帮我解决这个问题的人。 谢谢