R 如何在ggplot2中绘制组内的非线性回归线和总数据?
我有一个简单的数据集,有两个连续变量(囊泡和细胞),一个分组变量有两个水平(HC和RA),模拟如下:R 如何在ggplot2中绘制组内的非线性回归线和总数据?,r,ggplot2,nls,R,Ggplot2,Nls,我有一个简单的数据集,有两个连续变量(囊泡和细胞),一个分组变量有两个水平(HC和RA),模拟如下: ###Simulate Vesicle variable### Vesicle.hc <- sort(runif(23, 0.98, 5)) #HC group Vesicle1.ra <- sort(runif(5, 0.98, 3)) #RA group Vesicle <- c(Vesicle.hc, Vesicle1.ra) #Combined ###Simulat
###Simulate Vesicle variable###
Vesicle.hc <- sort(runif(23, 0.98, 5)) #HC group
Vesicle1.ra <- sort(runif(5, 0.98, 3)) #RA group
Vesicle <- c(Vesicle.hc, Vesicle1.ra) #Combined
###Simulate Cells variable###
z <- seq(23)
Cells.hc <- (rnorm(23, 50 + 30 * z^(0.2), 8))*runif(1, 50000, 400000) #HC group
Cells.ra <- c(8.36e6, 6.35e6, 1.287e7, 1.896e7, 1.976e7) #RA group
Cells <- c(Cells.hc, Cells.ra) #Combined
###Define groups and create dataframe###
Group <- rep("HC",23) #HC group
Group1 <- rep("RA",5) #RA Group
Group <- c(Group, Group1) #Combined
df <- data.frame(Cells, Vesicle, Group) #Data frame
我的问题是,除了绘制各组的非线性回归函数外,我如何绘制一条适合所有数据的回归线,即忽略分组变量的影响对数据进行建模
ggplot(df, aes(x = Cells, y = Vesicle, colour=Group)) +
xlab("Stimulated neutrophils") +
ylab("MV/cell") +
stat_smooth(method = 'nls', formula = 'y~a*exp(b*x)',
method.args = list(start=c(a=0.1646, b=9.5e-8)), se=FALSE) +
stat_smooth(color = 1, method = 'nls', formula = 'y~a*exp(b*x)',
method.args = list(start=c(a=0.1646, b=9.5e-8)), se=FALSE) +
geom_point(size=4, pch=21,color = "black", stroke=1.5, aes(fill=Group))
在创建
Cells.hc
的过程中,出现了一个意外的符号。另外,我不知道在哪里创建了z
。哦,我诚挚的道歉,当我制作工作示例时,我的环境中已经有了这些变量-我真是太草率了。编辑后的代码现在应该可以工作了。我尝试了你的建议@Axeman,但尽管没有抛出错误,情节也没有改变。谢谢。所以只需添加“color=1”就可以防止stat_smooth继承组分类。是的,就是这样。还有一个inherit.aes
参数,但这意味着您必须再次定义x
和y
,因此通常更容易使分组无效。
ggplot(df, aes(x = Cells, y = Vesicle, colour=Group)) +
xlab("Stimulated neutrophils") +
ylab("MV/cell") +
stat_smooth(method = 'nls', formula = 'y~a*exp(b*x)',
method.args = list(start=c(a=0.1646, b=9.5e-8)), se=FALSE) +
stat_smooth(color = 1, method = 'nls', formula = 'y~a*exp(b*x)',
method.args = list(start=c(a=0.1646, b=9.5e-8)), se=FALSE) +
geom_point(size=4, pch=21,color = "black", stroke=1.5, aes(fill=Group))