2013-02-21 581 views
3

我试图用ggplot2绘制一组数据。数据分为两类。我想用一条线性回归线将它们一起绘制。不过,我想让这两个小组中的每一个都以不同的颜色绘制。这里就是我得到:用ggplot2绘制带有两种不同颜色的单线

enter image description here

这里就是我得到了它:

library(ggplot2) 
dframe1 <- structure(list(a = 1:6, b = c(5, 7, 9, 10.5, 11.7, 17), category = structure(c(1L, 
1L, 1L, 2L, 2L, 2L), .Label = c("a", "b"), class = "factor")), .Names = c("a", 
"b", "category"), class = "data.frame", row.names = c(NA, -6L 
)) 
qplot(a, b, data = dframe1, colour = category) + geom_smooth(method = lm) 

如何让我的情节只使用一个回归线的所有数据?

注意:除此之外,我很困惑为什么这些行中只有一行显示置信区间,但这不是我当前问题的重点。

+4

关于你的注意:对于完美契合的信心乐队拥有零宽度。 – Roland 2013-02-21 17:59:34

回答

4

只需修改美学排除聚合因子:

qplot(a, b, data = dframe1, colour = category) + 
    geom_smooth(aes(colour=NA),method = lm) 

enter image description here

8

@罗兰的回答的等效,使用ggplot代替qplot

ggplot(dframe1, aes(x = a, y = b)) + 
    stat_smooth(method = lm) + 
    geom_point(aes(color = category)) 
+0

(+1)一旦避开'qplot'并使用'ggplot',理解语法就容易多了。 – Roland 2013-02-21 18:05:27

+0

(再次+1)同意。这两种解决方案都有效。事实上,我正在使用你的,但是因为罗兰正确地回答了这个问题,所以我将其标记为正确。 – CaptainProg 2013-02-22 11:26:40

相关问题