Ggplots日期格式化错误:%m/%y格式却按年份排序求助
ggplot日期排序问题解决方案
核心问题是你将日期转换为字符串类型后,ggplot会按字符串字典序排序(优先匹配月份数字,导致同月份不同年份的日期扎堆)。format()函数即便加上ordered=T,返回的仍是字符向量,无法保留时间顺序逻辑。
推荐解决方案:保留原生日期类型,仅调整显示格式
不要把日期转成字符串,保留Date类型,通过scale_x_date()设置x轴刻度的显示格式,既保证排序正确,又能显示成%m/%y样式:
# 保留原始日期类型,无需转成%m/%y字符串 countrydf$dates <- as.Date(countrydf$date, format="%Y-%m-%d") germanydf <- subset(countrydf, location == "Germany") ggplot(germanydf, aes(x=dates, y=total_deaths)) + geom_bar(stat = 'identity', position = 'dodge') + geom_smooth(method="lm", col="Grey", size=1) + labs(title="德国死亡人数随日期变化", subtitle="数据来源:ourworldindata.org", y="总死亡人数", x="日期") + # 设置x轴日期显示格式为%m/%y,可根据需求调整刻度间隔 scale_x_date(date_labels = "%m/%y", date_breaks = "1 month") + theme(axis.text.x = element_text(angle = 45, vjust = 0.5, hjust=.5))
备选方案:转为有序因子(不推荐)
如果一定要用字符串格式的日期,需将其转为有序因子,并按真实时间顺序定义因子水平:
# 先转成%m/%y字符串 countrydf$dates <- format(as.Date(countrydf$date, format="%Y-%m-%d"), "%m/%y") # 按原始日期的顺序,给因子设置正确的水平 countrydf$dates <- factor( countrydf$dates, levels = unique(countrydf$dates[order(as.Date(countrydf$date, format="%Y-%m-%d"))]), ordered = TRUE ) # 后续绘图代码不变 germanydf <- subset(countrydf, location == "Germany") ggplot(germanydf, aes(x=dates, y=total_deaths)) + geom_bar(stat = 'identity', position = 'dodge') + geom_smooth(method="lm", col="Grey", size=1) + labs(title="德国死亡人数随日期变化", subtitle="数据来源:ourworldindata.org", y="总死亡人数", x="日期") + theme(axis.text.x = element_text(angle = 45, vjust = 0.5, hjust=.5))
注:第一种方案更灵活,支持后续对日期做时间序列相关的操作(比如调整刻度间隔、过滤时间范围),优先推荐。
内容的提问来源于stack exchange,提问作者Donovan Morgan
相关产品推荐
相关产品推荐

