为何R语言中ggplot绘制的周期函数曲线呈现异常凹凸状?
解决R中ggplot绘制周期函数时stat_smooth曲线异常的问题
问题原因
stat_smooth 默认使用loess局部回归方法,它的设计目标是对带有噪声的散点数据进行趋势拟合。你的数据是严格符合周期函数的精确点,用局部回归拟合时,算法会在每个局部区间内调整曲线,反而破坏了周期函数原本的平滑性,导致出现凹凸不平的异常曲线。
解决方案
不需要用stat_smooth拟合,直接绘制已知的周期函数曲线即可,有两种常用方法:
方法1:使用geom_function直接调用函数
library(ggplot2) # 定义周期函数 test2 <- function(x) -23.5*cos(pi/4*x)+23.5 # 生成原始数据点 test_points <- data.frame(x = 0:32, y = test2(0:32)) ggplot(test_points, aes(x, y)) + geom_point() + geom_function(fun = test2, color = "#2196F3") # 直接绘制函数曲线
方法2:生成密集x值后用geom_line绘制
如果需要更精细的曲线,可以生成更密集的x序列,再用折线连接:
library(ggplot2) # 生成密集的x值(步长0.1,保证曲线平滑) x_dense <- seq(0, 32, by = 0.1) test_dense <- data.frame(x = x_dense, y = -23.5*cos(pi/4*x_dense)+23.5) # 原始数据点 test_points <- data.frame(x = 0:32, y = -23.5*cos(pi/4*(0:32))+23.5) ggplot() + geom_point(data = test_points, aes(x, y)) + geom_line(data = test_dense, aes(x, y), color = "#2196F3")
说明
- 两种方法都能得到和Desmos中一致的平滑周期曲线
stat_smooth适合处理带噪声的实验数据拟合趋势,不适合绘制已知的数学函数
内容的提问来源于stack exchange,提问作者Jakiepoo21
相关产品推荐
相关产品推荐

