对于这个数据集,我有一个具有 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"))
最佳答案
您无需为每个水平因子 (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)
关于r - 循环在ggplot中绘制几条拟合曲线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40552181/