如何在ggplot中使用scale_x_date自定义日期轴刻度标签
ggplot日期标签仅指定位置显示年份实现方案
你可以直接给scale_x_date传入自定义标签生成函数,判断每个刻度是否需要显示年份即可,修改后的完整代码如下:
library(ggplot2) library(dplyr) start_date <- as.Date('2020-08-08') end_date <- as.Date('2021-05-10') # 测试数据集 mytib <- tibble( dates = as.Date(as.character(seq(start_date, end_date, by = 4) ) ), yval = as.numeric(strftime(dates, format = "%d")), month = strftime(dates, format = "%m") ) %>% group_by( month ) gd <- ggplot(mytib, aes( x=dates, y=yval, color = month ) ) + geom_point() + geom_line( aes( x=dates, y=yval, color=month, group=month ) ) + theme(legend.position = "none") + scale_x_date(date_breaks = "1 month", date_minor_breaks = "1 week", # 自定义标签生成逻辑 labels = function(x) { # 提取刻度对应的月份数值 month_num <- as.integer(format(x, "%m")) # 判断是否为刻度序列的首尾值 is_first_last <- x %in% range(x) # 1月、12月、首尾刻度显示年份,其余仅显示月份 need_year <- month_num %in% c(1,12) | is_first_last return(ifelse(need_year, format(x, "%b %y"), format(x, "%b"))) }) + labs (x=NULL, y=NULL ) + geom_blank() gd
运行后生成的x轴标签会完全符合预期:Aug 20, Sep, Oct, Nov, Dec 20, Jan 21, Feb, Mar, Apr, May 21,不会出现标签拥挤问题。
内容的提问来源于stack exchange,提问作者donman
相关产品推荐
相关产品推荐

