r - 循环在ggplot中绘制几条拟合曲线?

标签 r ggplot2 nls

对于这个数据集,我有一个具有 3 个水平的因子 (iso) 和两个连续变量(温度和直径)

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)

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

有没有办法一次性绘制所有曲线,避免为每个水平因子(iso)重复相同的函数“+ geom_smooth(...)”?

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

最佳答案

您无需为每个水平因子 (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

关于r - 循环在ggplot中绘制几条拟合曲线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40552181/

相关文章:

r - 无法获得 flexdashboard modal Shiny react 性来处理 NULL 状态

r - 使用不同数据集的映射将列求和

r - ggplot 中的多个 geom_hline

r - 当 se.fit=TRUE 时,Predict 无法显示预测的标准误差

r - 2条曲线同时非线性回归

r - 将多个 data.frame 导出到多个 Excel 工作表的简单方法

R - 如何基于迭代更改列中的值

r - 仅将网格线添加到较小的中断处(ggplot)

r - ggplot 中的两个散点图,两个散点图之间有箭头

R:在 nlsLM() 语句内进行汇总