2013-02-21 584 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

相關問題