R语言正弦曲线拟合异常修复及ggplot2实现24小时全周期拟合求助
问题根因
- 拟合线出现跳转是因为原始数据
Time列是无序状态(顺序为17、9、20、12),R基础绘图的lines()函数会严格按照输入点的顺序连线,不会自动按横坐标值排序 - 要覆盖完整24小时周期,需要生成连续的1-24小时时间序列做预测,不能仅使用原始4个观测点的时间计算预测值
修正后基础R绘图代码
Test_case <- structure(list(TEST_RESULT = c(1.31, 65.44, 8.59, 9.91), Time = c(17, 9, 20, 12)), row.names = c(NA, -4L), class = c("tbl_df", "tbl", "data.frame")) # 拟合正弦模型 xc <- cos(2*pi*Test_case$Time/24) xs <- sin(2*pi*Test_case$Time/24) fit.lm <- lm(Test_case$TEST_RESULT ~ xc + xs) # 生成24小时连续序列做预测,步长0.1保证曲线平滑 full_time <- seq(1, 24, by = 0.1) full_xc <- cos(2*pi*full_time/24) full_xs <- sin(2*pi*full_time/24) full_pred <- predict(fit.lm, newdata = data.frame(xc = full_xc, xs = full_xs)) # 绘图 plot(TEST_RESULT ~ Time, data = Test_case, xlim = c(1,24), ylim = c(0,70), pch = 16) lines(full_time, full_pred, col = "blue", lwd = 2)
ggplot2 实现方案
library(ggplot2) # 构造预测结果数据框 pred_df <- data.frame( Time = full_time, TEST_RESULT = full_pred ) ggplot() + # 绘制原始观测点 geom_point(data = Test_case, aes(x = Time, y = TEST_RESULT), size = 3) + # 绘制平滑拟合正弦曲线 geom_line(data = pred_df, aes(x = Time, y = TEST_RESULT), color = "blue", linewidth = 1) + # 坐标轴配置 scale_x_continuous(breaks = seq(0, 24, 4), limits = c(1, 24), name = "时间(小时)") + scale_y_continuous(limits = c(0, 70), name = "检测结果") + theme_bw()
内容的提问来源于stack exchange,提问作者Kreitz Gigs
相关产品推荐
相关产品推荐

