为什么 geom_smooth 没有显示平滑线?

why geom_smooth not showing the smooth line?

我遇到了 geom_smooth() 无法处理我的 ggplot2 的问题。 但不是平滑的曲线,而是折叠。 我的X轴变量是因子变量(我试过转成数值变量,没成功),Y轴是数值变量。 我的 data.frame 是

ggplot(tmp, aes(x = x, y = y))+
  geom_point()+
  geom_smooth(formula = y ~ x, method = "loess", stat = "identity", se = T, group = "")

希望拍到这样的照片。

快速解决方法是将组包裹在 aes 中。生成了一个类似于您所拥有的结构的数据(一个因子 x 变量和一个数字 y 变量)。

set.seed(777)
x <- rep(c(LETTERS[1:7]), 3)
y <- rnorm(21, mean = 0, sd = 1)
tmp <- data.frame(x,y)
# -------------------------------------------------------------------------
base <- ggplot(tmp, aes(x = x, y = y))+geom_point()

base + geom_smooth(formula = y ~ x, method = "loess",se = TRUE, aes(group = "" ), level = 0.95) + theme_bw()

如果您想使用不同水平的置信区间,您可以更改水平值(默认为 95%)。

输出