You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言绘图中删除X轴上浇水前的时间刻度

解决方案
  • 第一步:明确数据结构
    假设你的数据框为soil_data,包含timestamp(时间戳,可选)和moisture(湿度值)两列;若无时间戳,用行索引定位即可。

  • 第二步:定位浇水节点(湿度突变上升点)
    浇水对应湿度大幅上升的位置,通过计算相邻湿度差值定位:

# 计算相邻湿度的差值
soil_data$diff <- c(0, diff(soil_data$moisture))

# 设定突变阈值(可根据数据调整,示例为均值+3倍标准差)
threshold <- mean(soil_data$diff, na.rm = TRUE) + 3*sd(soil_data$diff, na.rm = TRUE)

# 提取第一个超过阈值的位置,即浇水节点
watering_index <- which(soil_data$diff > threshold)[1]

若手动记录过浇水时间,直接匹配timestamp定位更精准。

  • 第三步:筛选浇水后的数据
# 保留浇水节点及之后的所有数据
filtered_data <- soil_data[watering_index:nrow(soil_data), ]

# 可选:删除临时生成的diff列
filtered_data$diff <- NULL
  • 第四步:绘图(两种常用方式)
    用ggplot2绘图:
library(ggplot2)

ggplot(filtered_data, aes(x = timestamp, y = moisture)) +
  geom_line(color = "#2E8B57") +
  labs(title = "浇水后土壤湿度变化", x = "时间", y = "湿度值") +
  theme_minimal()

用基础绘图工具:

plot(filtered_data$timestamp, filtered_data$moisture, type = "l", col = "darkgreen",
     main = "浇水后土壤湿度变化", xlab = "时间", ylab = "湿度值")
  • 特殊情况处理
    若数据存在误触导致的小幅度突变,可先平滑数据再定位:
# 用滑动窗口平滑湿度数据(窗口大小5,可调整)
soil_data$smoothed_moisture <- zoo::rollmean(soil_data$moisture, k = 5, fill = NA)
# 基于平滑数据计算差值找突变点
soil_data$smoothed_diff <- c(0, diff(soil_data$smoothed_moisture))
watering_index <- which(soil_data$smoothed_diff > threshold)[1]

内容的提问来源于stack exchange,提问作者Plant Man

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 13:27:04