Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

r - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...