ggplot:添加不同子集的回归线

时间:2017-02-09 09:13:16

标签: r ggplot2

我的问题: 我想显示两个不同组/组成的回归线。 我刚开始使用ggplot,因此对ggplot中的回归线知之甚少。

mel:
composition diametre    volume
mixed   0.261   71.3645893
mixed   0.233   392.9487358
mixed   0.319   284.8683927
pure    0.248   120.7654642
pure    0.274   142.1273373
pure    0.308   215.9924244
pure    0.188   26.11804847
pure    0.124   5.795590982
pure    0.307   136.7732086
pure    0.283   138.0600194
pure    0.175   32.43129359
pure    0.205   32.58726466
pure    0.159   12.27308951

下面的代码可以很好地显示散点图,但在添加geom_smooth(object 'volume' not found)时会产生错误;

ggplot(data = mel, aes(x=diametre, y=volume,col=as.factor(composition))) +
  geom_point()+
  geom_smooth (data =  subset(mel, composition=="mixed"), method='lm',
              formula= log(volume)~I(diametre^2),
              se=FALSE, size=2) +
  geom_smooth (data = subset(mel, composition=="pure"), method = "lm",
              formula = (volume)~I(diametre^2), se = FALSE, size = 2)

我认为可能发生了错误,因为我正在制作组合物?! 所以我尝试为每个组合使用一个表,因此代码看起来像这样

ggplot(data = mel, aes(x=diametre, y=volume,col=as.factor(composition))) +
  geom_point()+
  geom_smooth (data =  mel_mix, method='lm',
              formula= log(volume)~I(diametre^2),
              se=FALSE, size=2) +
  geom_smooth (data = mel_pure, method = "lm",
              formula = (volume)~I(diametre^2), se = FALSE, size = 2)

导致:invalid argument to unary operator

1 个答案:

答案 0 :(得分:1)

这应该可行(您需要x,y geom_smooth):

ggplot(data = mel, aes(x=diametre, y=volume,col=as.factor(composition))) +
  geom_point() +
  geom_smooth(method='lm',
              formula= log(y)~I(x^2),
              se=FALSE, size=2)

或者如果您想分别适合子集化数据:

ggplot(data = mel, aes(x=diametre, y=volume,col=as.factor(composition))) +
  geom_point()+
  geom_smooth (data =  subset(mel, composition=="mixed"), method='lm',
               formula= log(y)~I(x^2),
               se=FALSE, size=2) +
  geom_smooth (data = subset(mel, composition=="pure"), method = "lm",
             formula = log(y)~I(x^2), se = FALSE, size = 2)

但我认为volume~I(diametre^2)更适合您的数据:

ggplot(data = mel, aes(x=diametre, y=volume,col=as.factor(composition))) +
  geom_point() +
  geom_smooth(method='lm',
              formula= y~I(x^2),
              se=FALSE, size=2)

enter image description here