我正在尝试用我的数据框中的另一个变量替换多面堆叠条形图中的 x 轴刻度。我正在比较两个不同年份的相应周,所以我在 x 轴上使用“year”变量,在 y 轴上使用“total”变量,并按年份中的周数包装(即一月的第一周)得到数字 1,第二个是 2 等)。我已经尝试了很多东西,包括 scale_x_discrete;scale_x_date; axi.ticks.x、geom_text 等....
这是一个可重现的示例:
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))
dat %>% ggplot(aes(year, total, color = year == 2021)) +
geom_bar(position = "stack", stat = "identity", size =0.6)+
#scale_x_date(expand = c(0,0), labels = date_format("%m/%d/%y"))+
scale_y_continuous(expand = c(0,0), breaks = seq(0, 350000, by = 50000), limits=c(0, 350000))+
#scale_x_discrete(breaks = dat$year, labels = dat$date)+
scale_color_manual(values = c(NA, 'red'), guide=F)+
facet_wrap(~week, nrow = 1)+
#geom_text(aes(y= total, label = date), position = position_dodge(width = 1), angle = 90, vjust = -1, size = 2)+
theme(axis.text.x=element_text(angle = 90, vjust =0, hjust =0),
#axis.ticks.x = ,
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 轴显示一周的日期(该周的星期日日期)。所需的 x 轴刻度(请忽略上面的 *)
谢谢!
看起来您可以在这里使用离散的 x 轴,因为您不关心日期在时间轴上的位置,而只是按时间顺序排列类别。使用as.character(date)
可以实现这一点,或者您可以交换format(date, "%d-%b-%Y")
以复制示例中的日期格式。然后,您还需要 的scales = "free_x"
参数facet_wrap
,以便每个方面都可以仅显示出现在该方面的日期。
编辑:如果你想显示一个格式化的日期,但按时间顺序排列,你需要将格式化的日期变成一个因素。forcats::reorder()
给出了一种基于另一个变量来控制因子顺序的方法。
dat %>%
mutate(date_label = format(date, "%d-%b-%Y") %>% forcats::fct_reorder(date)) %>%
ggplot(aes(date_label, total, color = year == 2021)) +
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))+
scale_color_manual(values = c(NA, 'red'), guide=F)+
facet_wrap(~week, nrow = 1, scales = "free_x")+
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句