如何修改R语言ggplot2中facet_wrap分面堆叠条形图的x轴刻度
解决方案
你可以按以下步骤修改代码实现需求:
- 首先设置
facet_wrap的scales = "free_x"参数,允许每个分面独立设置x轴刻度标签 - 提前提取所有周数+年份组合对应的唯一日期,自定义
scale_x_discrete的标签生成逻辑,自动匹配每个分面对应的日期
修改后的完整可运行代码如下:
library(ggplot2) library(dplyr) dat <- data.frame(date = as.Date(c("2021-01-03", "2020-01-05", "2021-01-03", "2020-01-05", "2021-01-03", "2021-01-03", "2021-01-10","2020-01-12", "2021-01-10", "2020-01-12", "2021-01-10", "2021-01-10", "2021-01-17", "2020-01-19", "2021-01-17", "2020-01-19", "2021-01-17", "2021-01-17")), total = c(109334, 150052, 36546, 51476, 2961, 19988, 106719, 126748, 31893, 29576, 5401, 19336, 91021, 108892, 23030, 26115, 3861, 15663), product = c("A", "A","B", "B", "C", "D", "A", "A", "B", "B", "C", "D", "A", "A","B", "B", "C", "D"), week = c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3), year = c(2021,2020,2021,2020,2021,2021,2021,2020,2021,2020,2021,2021,2021,2020,2021,2020,2021,2021)) # 提前生成每个周和年份对应的唯一日期标签 date_labels <- dat %>% distinct(week, year, date) %>% # 可自行调整日期显示格式,这里示例为月/日/年 mutate(date_str = format(date, "%m/%d/%y")) dat %>% # x轴转因子保证2020在前、2021在后的固定顺序 ggplot(aes(factor(year), total, color = year == 2021, fill = product)) + geom_bar(position = "stack", stat = "identity", size =0.6)+ scale_y_continuous(expand = c(0,0), breaks = seq(0, 350000, by = 50000), limits=c(0, 350000))+ # 自定义x轴标签,匹配当前分面的周数对应的日期 scale_x_discrete( labels = function(x) { cur_week <- ggplot2::cur_data()$week[1] date_labels$date_str[date_labels$week == cur_week & date_labels$year == as.integer(x)] } ) + scale_color_manual(values = c(NA, 'red'), guide=F)+ # 允许分面使用独立x轴刻度 facet_wrap(~week, nrow = 1, scales = "free_x")+ theme(axis.text.x=element_text(angle = 90, vjust =0, hjust =0), axis.title.x = element_blank(), axis.title.y = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.spacing.x = unit(0.1, "lines"))
运行上述代码即可实现每个分面x轴显示对应周的两个年份的周日日期的效果。
内容的提问来源于stack exchange,提问作者Jota3go
相关产品推荐
相关产品推荐

