如何在R的lattice包中设置x轴日期为mm-dd-yy格式且仅显示每月首日?
解决Lattice双Y轴图表的X轴日期格式化问题
问题分析
你遇到的Error in multiple && !outer : invalid 'x' type in 'x && y'错误,是因为直接使用format(pretty(df$date), "%d-%m-%y")设置刻度时,传递了不符合Lattice预期的参数类型。Lattice的scales参数需要明确指定刻度位置(at,必须是POSIXct类型)和对应的标签(labels,字符类型),而不是直接将格式化后的字符串作为刻度位置。
解决方案
我们需要手动生成每月第一天的刻度位置,并将其格式化为mm-dd-yy样式,再应用到第一个绘图对象上(因为doubleYscale会沿用第一个图的X轴设置)。
完整代码
library(lattice) library(latticeExtra) # 加载样本数据 df <- structure(list(date = structure(c(1634688000, 1634774400, 1634860800, 1635033600, 1635120000, 1635206400, 1635379200, 1635465600, 1635638400, 1635811200, 1635897600, 1636070400, 1636416000, 1636502400, 1636588800, 1636675200, 1636934400, 1637020800, 1637107200, 1637280000, 1637366400, 1637625600, 1637712000, 1637971200, 1638057600, 1638144000, 1638230400, 1638316800, 1638403200), class = c("POSIXct", "POSIXt"), tzone = "UTC"), Nconc = c(2.63e-05, 2.4e-05, 1.83e-05, 1.47e-05, 2.11e-05, 2.09e-05, 3.99e-05, 5.22e-05, 9.17e-06, 2.89e-05, 4.79e-05, 1.9e-05, 3.12e-05, 1.81e-05, 5.79e-06, 4.49e-05, 7.61e-06, 1.51e-05, 3.61e-05, 1.46e-05, 1.16e-05, 3.53e-05, 0.000232, 3.09e-05, 1.31e-06, 1.24e-05, 4.99e-05, 7.76e-05, 0.00016 ), Sconc = c(2.98e-05, 2.79e-05, 1.75e-05, 2.2e-05, 2.62e-05, 2.56e-05, 4.27e-05, 5.6e-05, 1.26e-05, 3.92e-05, 6.11e-05, 1.42e-05, 2.53e-05, 2.12e-05, 4.31e-06, 4.57e-05, 9.83e-06, 1.07e-05, 3.65e-05, 2.51e-05, 1.23e-05, 2.63e-05, 0.000212, 3.99e-05, 1.42e-06, 1.08e-05, 4.09e-05, 7.89e-05, 0.000113 ), CountyCounts = c(46, 45, 47, 17, 49, 49, 29, 38, 19, 20, 30, 25, 38, 24, 19, 27, 27, 30, 39, 17, 11, 23, 21, 19, 21, 43, 45, 42, 28)), class = c("tbl_df", "tbl", "data.frame" ), row.names = c(NA, -29L)) # 生成每月第一天的X轴刻度 # 提取数据中所有唯一的年月组合 unique_ym <- unique(format(df$date, "%Y-%m")) # 转换为每月第一天的POSIXct对象(刻度位置) x_ticks <- as.POSIXct(paste0(unique_ym, "-01"), tz = "UTC") # 格式化为mm-dd-yy样式的标签 x_labels <- format(x_ticks, "%m/%d/%y") # 创建第一个绘图对象并应用自定义X轴刻度 obj1 <- xyplot(Nconc + Sconc ~ date, df, type = "l", main = "Title", lwd = 2, col = c("red", "steelblue"), scales = list(x = list(at = x_ticks, labels = x_labels))) # 创建第二个绘图对象 obj2 <- xyplot(CountyCounts ~ date, df, type = "l", lwd = 2, col = "green") # 组合双Y轴图表 p <- doubleYscale(obj1, obj2, use.style = FALSE, add.ylab2 = TRUE) p
关键步骤说明
- 生成刻度位置:通过提取数据中唯一的年月组合,构造出每月第一天的POSIXct对象,确保刻度位置是Lattice能识别的日期类型。
- 格式化标签:使用
format()将刻度位置转换为mm-dd-yy格式的字符串,作为X轴显示的标签。 - 应用到绘图对象:在第一个
xyplot中通过scales参数指定X轴的刻度位置和标签,doubleYscale会自动沿用这个X轴设置。
内容的提问来源于stack exchange,提问作者BHope
相关产品推荐
相关产品推荐

