使用ggplot2为每个组添加回归线

19

我做了以下这张图:

> ddd
      UV.NF TRIS            volvol
2  145.1923   31  500 µl / 625  µl
3  116.3462   50  500 µl / 625  µl
4  127.1635   60  500 µl / 625  µl
5  125.9615   69  500 µl / 625  µl
6  162.0192   30    1 ml / 625  µl
7  166.8269   50    1 ml / 625  µl
8  176.4423   60    1 ml / 625  µl
9  171.6346   70    1 ml / 625  µl
19 292.3077   31 500 µl / 2500  µl
20 321.1538   50 500 µl / 2500  µl
21 225.0000   60 500 µl / 2500  µl
22 263.4615   69 500 µl / 2500  µl
23 301.9231   30   1 ml / 2500  µl
24 350.0000   50   1 ml / 2500  µl
25 282.6923   60   1 ml / 2500  µl
26 282.6923   70   1 ml / 2500  µl
35 133.6207   31  500 µl / 625  µl

ggplot() +  
    geom_point(aes(y = log(UV.NF), x = TRIS, colour=ddd[,"volvol"], shape=ddd[,"volvol"]), 
        data=ddd) + 
    labs(colour = "volvol", shape="volvol") + xlab("TRIS (mM)") + 
    guides(colour = guide_legend(title="Vol. lyo. / Vol. reconst."), 
        shape=guide_legend(title="Vol. lyo. / Vol. reconst.")) +
    scale_shape_manual(values = c(19,19,3,3)) + scale_colour_manual(values = c(2,4,2,4))

图表

我想为图例中出现的四个组别中的每个组别添加回归线lm(y~x)。我已经尝试了许多次使用geom_smooth(),但没有成功。

1个回答

30

我不太确定那是否符合你的要求,但你是否尝试过以下方法?

ggplot(ddd,aes(y = log(UV.NF), x = TRIS, colour = volvol, shape = volvol)) +
   geom_point() + geom_smooth(method = "lm", fill = NA)

这将使用您的数据生成以下图表:enter image description here

还有一些文档介绍geom_smooth,该函数可以以更为复杂(但也更加灵活)的方式实现您所需的功能。


请注意,由于数据点太少,线性模型的精度不是很高。 - Aleksandar Dimitrov
2
太好了!那不起作用是因为我输入了 ggplot() + geom_point(...) 而不是 ggplot(...) + geom_point()。 - Stéphane Laurent
3
除非你有非常好的理由(比如想在同一张图上放置不同种类的图形),否则应该始终将数据和通用美学设置(aes())放在ggplot函数中。这时,把aes()放在各自的geom_ *函数中会更加合理。 - Aleksandar Dimitrov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接