如何将海狮观测点叠加到geom_line()绘制的潮汐高度图上?
解决方案
核心逻辑是:观测点的y值不再使用计数数值,而是根据观测时间匹配对应时刻的潮汐高度,让点直接落在潮汐曲线上对应的位置,从而共用同一个y轴。
1. 安装加载所需扩展包
除了已有的ggplot2和scales,还需要dplyr处理数据,lubridate处理时间:
install.packages(c("dplyr", "lubridate")) # 首次使用需安装 library(dplyr) library(lubridate)
2. 匹配观测时间与潮汐高度
由于观测时间和潮汐数据的时间点不完全重合,用线性插值的方式为每个观测时间点匹配对应的潮汐高度:
# 提取潮汐数据的时间和高度用于匹配 tide_ref <- tidedata %>% select(date, height) # 处理观测数据:去掉NA值,添加匹配的潮汐高度 countDF.melt <- countDF.melt %>% filter(!is.na(value)) %>% # 过滤无计数的NA行 mutate( # 用线性插值计算对应时间的潮汐高度 tide_height = approx( x = tide_ref$date, y = tide_ref$height, xout = countDate )$y )
如果观测时间和潮汐数据的时间完全一致,可直接用left_join()替代插值:
countDF.melt <- countDF.melt %>% filter(!is.na(value)) %>% left_join(tide_ref, by = c("countDate" = "date")) %>% rename(tide_height = height)
3. 修改绘图代码,移除次坐标轴
现在观测点的y值用匹配到的tide_height,即可和潮汐曲线共用同一个y轴:
plot <- ggplot() + theme_light() + # 绘制潮汐高度曲线 geom_line(data = tidedata, aes(x = date, y = height, group = 1), color = 'blue') + # 绘制观测点:y用匹配的潮汐高度,形状按物种分类 geom_point(data = countDF.melt, aes(x = countDate, y = tide_height, shape = factor(variable, labels = c("加州海狮","北海狮","未知物种"))), size = 3, # 调大点更醒目 alpha = 0.8) + # 半透明避免遮挡曲线 # 设置标签与标题 labs( x = "日期", y = "潮汐高度(英尺)", shape = "海狮物种", title = "驳船上海狮计数与潮汐高度" ) + # 时间轴设置 scale_x_datetime( breaks = date_breaks("1 days"), labels = date_format("%d - %b"), # 月份缩写更规范 expand = c(0,0), limits = c(as.POSIXct("2020-12-09 00:00:00"), as.POSIXct("2020-12-15 23:00:00")) ) + # 主题调整 theme( plot.title = element_text(hjust = 0.5, size = 14, face = "bold"), axis.text.x = element_text(angle = 45, hjust = 1, size = 10), axis.title = element_text(size = 12) ) # 显示图形 print(plot)
额外优化建议
- 若需要显示计数数值,可添加文本标签:
geom_text(data = countDF.melt, aes(x = countDate, y = tide_height, label = value), vjust = -1, size = 3) - 可为不同物种设置自定义颜色:在
geom_point()的aes中添加color = factor(variable,...),再用scale_color_manual(values = c("red", "green", "gray"))设置颜色 - 若插值结果不理想,可尝试用
zoo包的na.approx()或rollmean()做更平滑的时间匹配
内容的提问来源于stack exchange,提问作者mcdejer
相关产品推荐
相关产品推荐

