R:stat_smooth组(x轴)

问题描述 投票:8回答:1

我有一个Database,并想使用stat_smooth显示一个图形。

我可以显示avg_time与Scored_Probabilities数字,如下所示:

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

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9ZQTdGNy5wbmcifQ==” alt =“在此处输入图像描述”>

但是将平均时间更改为时间或年龄时,会发生错误:

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)?

我该如何解决?

r ggplot2 smooth stat
1个回答
10
投票

错误消息说要设置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

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9ZVDRmTy5qcGcifQ==” alt =“在此处输入图像描述”>

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

请注意as.numeric的使用,因为Age是一个因素。

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9QQkxxUS5qcGcifQ==” alt =“在此处输入图像描述”>

© www.soinside.com 2019 - 2024. All rights reserved.