如何用R的ggplot绘制x轴不按字母排序的时序图表?
解决ggplot中X轴日期按字母排序的问题
你的核心问题是date列属于字符串类型,ggplot会默认按字母顺序对其排序。以下两种方案可解决该问题:
方案一:转为真正的日期类型(推荐)
将Year和Month组合成可识别的日期格式,ggplot会自动按时间顺序排列,后续还能方便进行时间序列相关操作:
# 先安装并加载lubridate包(如果未安装) # install.packages("lubridate") library(lubridate) library(ggplot2) # 直接将年份和月份转为日期(默认取当月第一天) df$date <- ymd(paste(data$Year, data$Month, "01", sep = "-")) df_new <- df[c("date", "BrisMaxTemp", "GoldCoastMaxTemp")] ggplot(df_new, aes(x = date, y = BrisMaxTemp)) + geom_point() + ylab("Bris Max Temp (°C)") + theme(axis.text.x = element_text(angle = 90, color = "Black", size = 10, face = 3)) + ggtitle("Brisbane Max temps over time") + xlab("Year_Month") + # 自定义X轴刻度显示为「年份_月份缩写」格式 scale_x_date(date_labels = "%Y_%b")
方案二:正确设置因子的水平顺序
如果坚持使用Year_Month字符串格式,需要先生成按时间排序的水平列表,再将date转为因子:
library(ggplot2) # 生成所有唯一的Year_Month组合,并按时间排序 ordered_dates <- unique(paste(data$Year, data$Month, sep = "_")) ordered_dates <- ordered_dates[order(as.Date(paste(ordered_dates, "01", sep = "-")))] # 将date列转为因子,指定水平为排序后的列表 df$date <- factor(df$date, levels = ordered_dates) df_new <- df[c("date", "BrisMaxTemp", "GoldCoastMaxTemp")] ggplot(df_new, aes(x = date, y = BrisMaxTemp)) + geom_point() + ylab("Bris Max Temp (°C)") + theme(axis.text.x = element_text(angle = 90, color = "Black", size = 10, face = 3)) + ggtitle("Brisbane Max temps over time") + xlab("Year_Month")
为什么之前用factor无效?
你之前的factor操作未指定levels参数,默认会按字符串的字母顺序生成水平,自然无法得到正确的时序排序。必须先构建按时间先后排列的levels列表,再传给factor函数。
内容的提问来源于stack exchange,提问作者Oskar Clare
相关产品推荐
相关产品推荐

