R: stat_smooth组 (x轴)

9
我有一个数据库,想要使用stat_smooth显示一个图形。
我可以展示avg_time与Scored_Probabilities之间的图形,看起来像这样:
c <- ggplot(dataset1, aes(x=Avg.time, y=Scored.Probabilities))
c + stat_smooth()

但是当将“平均时间”更改为“时间”或“年龄”时,会出现错误:
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)?

如何解决这个问题?

stat_smooth 只能处理连续型变量。您的 age 变量是字符型变量。我只能假设 time 变量也不是保存为时间格式,而是字符型变量。您首先需要以有意义的方式将变量转换为数值型。 - shadow
1个回答

13

错误信息提示设置group=1,但这样做会出现另一个错误。

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.

现在唯一的x值数量不足。

因此有两种解决方案:i) 使用另一个函数,例如mean,ii) 使用抖动略微移动年龄。

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

在此输入图片描述

或者

ggplot(dataset1, aes(x=jitter(as.numeric(as.character(Age))), y=Scored.Probabilities, group=1))+
geom_point()+stat_smooth() 
注意使用 as.numeric ,因为 Age 是一个因子(factor)。 enter image description here

1
在一个因子上使用 as.numeric(as.character(variable))as.numeric(variable) 可能无法返回预期的值。 - moodymudskipper
1
你可能是对的,随意编辑答案。 - Mamoun Benghezal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接