如何在ggplot wrap中添加回归线

时间:2013-11-19 17:02:26

标签: r ggplot2

我在向我的ggplots添加线性回归线时遇到了麻烦。 它应该是这样的: enter image description here

目前的情况如下: enter image description here

这是我的代码:

p <- ggplot(data = wage, aes(x = educ, y = lwage, colour = black, 
                cex = IQ, pch = married, alpha = 0.7)) + geom_jitter() 

p1 <- p + facet_grid(urban~experclass) + geom_smooth(se=F,method="lm") 

p1 + labs(x = "Education (year)", y = "Log Wage", shape = "Marital status",
          colour = "Ethnicity") + guides(alpha = FALSE)

geom_smooth的位置错了吗?我想要的只是绘图中每个元素的一条黑色回归线 - 而不是一层一层。

此外,当我添加回归线时会发生图例符号更改。尤其是IQ传奇看起来很奇怪。有没有我在这里没有考虑的事情?

应该如何看待:

enter image description here

外观如何:

enter image description here

1 个答案:

答案 0 :(得分:0)

我可以尝试回答你问题的至少一部分 - 这是关于绘制一个回归线而不是每个面板两个回归线的部分。我没有你的数据所以我不能完全复制你的问题,但我认为这将有效。

原始ggplot()调用中的美学将由所有后续层继承,包括geom_smooth。 您似乎想要的是颜色美学(恰好是分组标识符)仅应用于抖动点而不是线。所以你可以像这样写代码:

    p <- ggplot(data = wage, aes(x = educ, y = lwage, 
            cex = IQ, pch = married, alpha = 0.7)) + 
            geom_jitter() 

    p1 <- p + facet_grid(urban~experclass) + 
           geom_smooth(se=F,method="lm",
           aes(colour = black))

或者,作为一个修改样式的单个ggplot调用:

    p3 <- ggplot(data = wage, 
                 aes(x = educ, y = lwage, 
                  size = IQ, shape = married, alpha = 0.7)) + 
           geom_jitter() + 
           geom_smooth(se=F,method="lm",
                       aes(colour = black))+
           facet_grid(urban~experclass)
    p3