Eric
Eric

Reputation: 1389

how to force geom_smooth render for ggplot?

I would like to force render a smoother line for this multi-group plot, even in situations where a group has only one or two values. see below:

library(ggplot2)

set.seed(1234)
df <- data.frame(group = factor(c(rep("A",3),rep("B",2),"C")), x = c(1,2,3,1,2,2), value = runif(6))
ggplot(df,aes(x=x,y=value,group=group,color=group))+
  geom_point(size=2)+
  geom_line(stat="smooth",method = "loess",size = 2, alpha = 0.3)

enter image description here

Here's The output I want to see:

enter image description here

Upvotes: 4

Views: 1046

Answers (1)

Uwe
Uwe

Reputation: 42592

The call gives a lot of warnings which can be inspected by warnings(). One of the warnings says "zero-width neighborhood. make span bigger".

So, I tried OP's code with the additional span = 1 parameter:

library(ggplot2)
ggplot(df, aes(x = x, y = value, group = group, color = group)) +
  geom_point(size = 2) +
  geom_line(
    stat = "smooth",
    method = "loess",
    span = 1,
    size = 2,
    alpha = 0.3
  )

and got smoothed curves for groups A and B with only 3 and 2 data points, resp.

enter image description here

Upvotes: 5

Related Questions