如何用base R的plot()为周数据添加唯一等距的月年轴标签
问题
需要用base R的plot()函数绘制散点图,要求如下:
- X轴为156周的日期数据(约3年,起始于2020年3月19日的周区间)
- Y轴为
cases数值,数据点用圆点表示 - 禁止使用ggplot2包
当前尝试将文本日期转为Date格式后直接绘图,但X轴出现重复的月年标签或间距不均的刻度,希望仅显示36个唯一的月年轴标签,寻求base R中类似ggplot2里scale_x_date的实现方式。
示例数据
Lines <- "Week_Interval Cases Week_Start 19-01-03-19-01-09 696537 2019-01-03 19-01-03-19-01-09 718748 2019-01-10 19-01-17-19-01-23 799355 2019-01-17 19-01-24-19-01-30 805800 2019-01-24 19-01-31-19-02-06 701262 2019-01-31 19-02-07-19-02-13 531579 2019-02-07 19-02-14-19-02-20 690068 2019-02-14 19-02-21-19-02-27 756947 2019-02-21 19-02-28-19-03-06 718757 2019-02-28 9-03-07-19-03-13 701768 2019-03-07 19-03-14-19-03-20 820113 2019-03-14 19-03-21-19-03-27 645259 2019-03-21" exampledata <- read.table(textConnection(Lines), header = TRUE)
初始绘图代码
exampledata$Date <- as.Date(exampledata$Week_Start) # Plot outcome variable versus time plot(exampledata$Date,exampledata$Cases, main="Weeks by Cases", ylab="Cases", ylim=c(500000,900000), xlab="", las=2, col="red", xaxt="n") # Add x-axis year labels axis(1, exampledata$Date, format(exampledata$Date, "%b, %Y")) # Add in the points for the figure points(exampledata$Date,exampledata$Cases, col="red", pch=20)
解决方案
在base R中可以通过手动生成均匀的日期刻度序列实现类似scale_x_date的效果,步骤如下:
- 提取数据的日期范围,生成每月第一天的序列(3年正好对应36个刻度)
- 用
axis()函数指定这些序列作为刻度位置,格式化标签为月年格式 - 调整标签显示方式避免重叠
修改后的完整代码
# 转换日期格式 exampledata$Date <- as.Date(exampledata$Week_Start) # 生成每月第一天的刻度序列(覆盖数据的日期范围) date_range <- range(exampledata$Date) monthly_ticks <- seq( from = as.Date(paste0(format(date_range[1], "%Y-%m"), "-01")), to = date_range[2], by = "month" ) # 绘制基础散点图,关闭默认X轴 plot(exampledata$Date, exampledata$Cases, main = "周度病例数趋势", ylab = "病例数", ylim = c(500000, 900000), xlab = "日期", las = 2, col = "red", pch = 20, xaxt = "n" # 关闭默认X轴 ) # 添加自定义X轴刻度与标签 axis(1, at = monthly_ticks, labels = format(monthly_ticks, "%b %Y"), cex.axis = 0.8 # 可选:缩小标签字号避免重叠 ) # 添加网格线(可选,提升可读性) grid(nx = NA, ny = NULL)
代码说明
monthly_ticks:生成从数据起始月第一天到结束日期的每月日期序列,确保刻度均匀且数量符合36个的需求axis(1, at = monthly_ticks, ...):指定刻度位置为每月第一天,标签格式化为"月 年"(如Jan 2019)cex.axis:当标签过多时,可通过缩小字号避免重叠,可根据实际显示效果调整参数值
内容的提问来源于stack exchange,提问作者Fable
相关产品推荐
相关产品推荐

