我之前尝试用 loess 和 lm 方法 (ggplot2) 拟合我的数据,但是这些方法都不适合。现在我正在尝试为数据拟合饱和曲线,但找不到方法来做到这一点。谷歌搜索一段时间后,我想知道这是否可以使用 ggplot2。否则我想过拟合逻辑回归,并尝试过这个,但不幸的是给了我以下错误:
这会使用 loess 方法生成想要的图。如何用饱和度曲线绘制它?
specprec <- ggplot(data=master, aes(prec_average, binomial_c))+
geom_point(size=1.3, shape=16)+
theme_bw(base_size = 14)+
theme(aspect.ratio=1)+
labs(x="Mean precipitation", y="Species richness")+
stat_smooth(method="loess")
这是我尝试拟合逻辑回归曲线的方法:
m <- glm(prec_average ~ binomial_c, family = gaussian, data = master)
p_specprec <- augment(m, type.predict = "response")
head(p_specprec)
base <-
ggplot(p_specprec, aes(x = prec_average, y=m)) +# geom_line(aes(y = m), color = "blue") +
labs(x = "Mean precipitation", y = "Species richness")
Error: Don't know how to automatically pick scale for object of type glm/lm. Defaulting to continuous.
Error: Aesthetics must be either length 1 or the same as the data (4538): y
任何提示都会有很大帮助!提前致谢!
答案 0 :(得分:1)
出现错误是因为您试图绘制模型 m
而不是数据框 p_specprec
中的列。
由于我无法访问您的数据,因此我使用了 mtcars 并重新标记了一些列。
library(ggplot)
master <- mtcars
master<- master %>% rename(prec_average = mpg, binomial_c = disp)
您还需要包含库 broom
以使扩充工作。
library(broom)
定义模型,并将结果转化为数据框。
m <- glm(prec_average ~ binomial_c, family = gaussian, data = master)
p_specprec <- augment(m, type.predict = "response")
这里使用 ggplot,我们指定要在美学中使用的数据和列。
我猜您想针对其位于 prec_average
的拟合值绘制 p_specprec$.fitted
,还请注意,在 geom_line() 中,您不需要再次指定美学。
ggplot(p_specprec, aes(x = prec_average, y=.fitted)) +
geom_line(colour = 'blue')+
labs(x = "Mean precipitation", y = "Species richness")