Search code examples
rggplot2smoothing

why geom_smooth not showing the smooth line?


I am having a problem where geom_smooth() is not working on my ggplot2. But instead of a smooth curve, there is a fold. enter image description here My X-axis variable is the factor variable(I've tried to convert it to a numerical variable, but it didn't work), and Y-axis is numeric variable. My data.frame is that enter image description here enter image description here

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

I hope to get a pic like this. enter image description here


Solution

  • A quick fix will be to wrap the group inside aes. Generated a data similar to the structure you have (a factor x variable and a numeric y var).

    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()
    

    If you want to use a different level of confidence interval, you can change the value of level (which is a 95% by default).

    Output

    geom_smooth_output