R : stat_smooth groups (x axis)
Asked Answered
C

1

9

I have a Database, and want to show a figure using stat_smooth.

I can show the avg_time vs Scored_Probabilities figure, which looks like this:

c <- ggplot(dataset1, aes(x=Avg.time, y=Scored.Probabilities))
c + stat_smooth()

enter image description here

But when changing Avg.time to time or Age, an error occurs:

c <- ggplot(dataset1, aes(x=Age, y=Scored.Probabilities))
c + stat_smooth()
error: geom_smooth: Only one unique x value each group. Maybe you want aes(group = 1)?

How could I fix it?

Crosslink answered 13/5, 2015 at 7:44 Comment(1)
stat_smooth only works with continuous variables. Your age variable is a character variable. I can only assume that the time variable is also not saved as time, but character instead. You first have to convert your variables to numeric in a meaningful way.Alarice
O
13

the error message says to set group=1, doing that gives another error

ggplot(dataset1, aes(x=Age, y=Scored.Probabilities, group=1))+stat_smooth()
geom_smooth: method="auto" and size of largest group is >=1000, so using gam with formula: y ~ s(x, bs = "cs"). Use 'method = x' to change the smoothing method.
Error in smooth.construct.cr.smooth.spec(object, data, knots) : 
  x has insufficient unique values to support 10 knots: reduce k.

Now the number of unique x values is not enough.

So two solutions : i) using another function like mean, ii) using jitter to move slightly Age.

ggplot(dataset1, aes(x=Age, y=Scored.Probabilities, group=1))+
geom_point()+
stat_summary(fun.y=mean, colour="red", geom="line", size = 3) # draw a mean line in the data

enter image description here

Or

ggplot(dataset1, aes(x=jitter(as.numeric(as.character(Age))), y=Scored.Probabilities, group=1))+
geom_point()+stat_smooth() 

Note the use of as.numeric because Age is a factor.

enter image description here

Olag answered 13/5, 2015 at 8:23 Comment(2)
on a factor use as.numeric(as.character(variable)), as.numeric(variable) may not return the expected valueAllare
you are probably right, feel free to edit the answerOlag

© 2022 - 2024 — McMap. All rights reserved.