簡體   English   中英

在R中的圖上繪制對數曲線

[英]Draw a logarithmic curve on graph in R

我有以下數據集,並且繪制時具有曲線關系

Fish.species.richness   Habitat.Complexity  log.habitat
17  0.6376  -0.1954858
13  0.2335  -0.6317131
30  0.2866  -0.5427238
20  0.3231  -0.4906630
22  0.1073  -0.9694003
25  0.2818  -0.5500590
2   0.2182  -0.6612448
4   0.0189  -1.7246886
19  0.2960  -0.5287083
25  0.5507  -0.2590849
29  0.2689  -0.5704900
21  0.6286  -0.2016602
18  0.1557  -0.8078509
24  0.6851  -0.1642460
30  0.5059  -0.2959353
32  0.4434  -0.3532043
29  0.3585  -0.4455108
32  0.5920  -0.2276783

當我記錄x軸並進行線性回歸以找到截距和斜率時,我能夠添加適合數據的線:

summary(lm(Fish.species.richness~log.habitat,data=three))

plot(three$log.habitat,
 three$Fish.species.richness,
 xlab='Log Habitat Complexity',
 ylab='Fish Species Richness')
abline(29.178,13.843)

然而,當我進行曲線回歸並嘗試繪制曲線時,它不適合數據,我哪里出錯了?

mod.log<-lm(Fish.species.richness~log(Habitat.Complexity),data=three)

plot(three$Habitat.Complexity,
 three$Fish.species.richness)
abline(mod.log)

使用ggplot2

ggplot(three, aes(Habitat.Complexity, Fish.species.richness))+
  geom_point(shape = 1) + stat_smooth(method = "lm", formula = y ~ log(x))

在此輸入圖像描述

abline只能繪制直線,形式為y = a + bx 可以使用curve函數添加其他曲線。

plot(Fish.species.richness ~ Habitat.Complexity, three)
curve(coef(mod.log)[1] + coef(mod.log)[2]*log(x), add=TRUE)

對數曲線擬合

為了清晰和靈活地使用其他模型類型,您可能希望使用predict函數來計算預測變量范圍內的預測值:

mod.log<-lm(Fish.species.richness~log(Habitat.Complexity), data=three)

# predict along predictor variable range
newdat <- data.frame(Habitat.Complexity=seq(min(three$Habitat.Complexity), max(three$Habitat.Complexity),,100))
newdat$Fish.species.richness <- predict(mod.log, newdat, type="response")

# plot
plot(Fish.species.richness ~ Habitat.Complexity, data=three)
lines(Fish.species.richness ~ Habitat.Complexity, data=newdat)

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM