3

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

3
  • 1
    Delete stat = "identity" and group = "" Commented Aug 24, 2019 at 7:10
  • Tested deleting the stat = "identity" and group = " ", and doing that alone isn't producing the desired output shown in the question. Just pointing that out, and that can be verified using a df with a similar structure as the question. Commented Aug 24, 2019 at 11:18
  • I have solved my problem by modifying the X-axis (1:n instead of the original factor coordinates).But thx all of U. Commented Aug 25, 2019 at 9:51

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

5 Comments

Thx, your answer helped me a lot!!
But I have a new question, why the line is not a smooth line but a fold line in your pic?
I seem to understand that if I want to get a smooth curve, my X-axis has to be a numerical variable rather than a factor coordinate.
If you want a straight line, change the method to lm which is a linear fitting than the loess which uses a different estimate for the fitting line (polynomial regression fitting).
@C.chen if you're satisfied with the answer, you might want to up-vote and mark it as an answer by clicking the right mark below the up-vote button.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.