循环绘制ggplot中的几条拟合曲线?

时间:2016-11-11 16:25:06

标签: r ggplot2 nls

使用此数据集,我有一个3级(iso)因子和两个连续变量(temp和diam)

library(ggplot2)
library(nlme)

zz <-(" iso temp diam
 Itiquira   22  5.0
 Itiquira   22  4.7
 Itiquira   22  5.4
 Itiquira   25  5.8
 Itiquira   25  5.4
 Itiquira   25  5.0
 Itiquira   28  4.9
 Itiquira   28  5.2
 Itiquira   28  5.2
 Itiquira   31  4.2
 Itiquira   31  4.0
 Itiquira   31  4.1
 Londrina   22  4.5
 Londrina   22  5.0
 Londrina   22  4.4
 Londrina   25  5.0
 Londrina   25  5.5
 Londrina   25  5.3
 Londrina   28  4.6
 Londrina   28  4.3
 Londrina   28  4.9
 Londrina   31  4.4
 Londrina   31  4.1
 Londrina   31  4.4
    Sinop   22  4.5
    Sinop   22  5.2
    Sinop   22  4.6
    Sinop   25  5.7
    Sinop   25  5.9
    Sinop   25  5.8
    Sinop   28  6.0
    Sinop   28  5.5
    Sinop   28  5.8
    Sinop   31  4.5
    Sinop   31  4.6
    Sinop   31  4.3"
)
df <- read.table(text=zz, header = TRUE)

我为每个因子水平拟合一条曲线,我需要将它们绘制在同一图形中。

有没有办法做到这一点下一次绘制所有曲线,避免重复相同的功能&#34; + geom_smooth(...)&#34;对于每个级别因子(iso)?

daf <- groupedData(diam ~ temp | iso, data = df, order = FALSE) 

ip <- ggplot(data=daf,  aes(x=temp, y=diam, colour = iso)) +  
  geom_point() + facet_wrap(~iso)

ip + geom_smooth(method = "nls", 
                method.args = list(formula = y ~ thy * exp(thq * (x-thx)^2 + thc * (x - thx)^3), 
                                   start = list(thy=5.4, thq=-0.01, thx=25, thc=0.0008)),
                se = F, size = 0.5, data = subset(daf, iso=="Itiquira")) +

  geom_smooth(method = "nls", 
              method.args = list(formula = y ~ thy * exp(thq * (x-thx)^2 + thc * (x - thx)^3), 
                                 start = list(thy=5.4, thq=-0.01, thx=25, thc=0.0008)),
              se = F, size = 0.5, data = subset(daf, iso=="Londrina")) +

  geom_smooth(method = "nls", 
              method.args = list(formula = y ~ thy * exp(thq * (x-thx)^2 + thc * (x - thx)^3), 
                                 start = list(thy=5.4, thq=-0.01, thx=25, thc=0.0008)),
              se = F, size = 0.5, data = subset(daf, iso=="Sinop")) 

enter image description here

1 个答案:

答案 0 :(得分:4)

您可以获得相同的图,而不必为每个级别因子(iso)重复相同的功能,如下所示:

ggplot(data=daf,  aes(x=temp, y=diam, colour = iso)) +  
  geom_point() +
  facet_wrap(~iso) +
  geom_smooth(method="nls",
              method.args=list(formula=y ~ thy * exp(thq * (x-thx)^2 + thc * (x - thx)^3), 
                                 start=list(thy=5.4, thq=-0.01, thx=25, thc=0.0008)),
              se = F, 
              size = 0.5)

enter image description here