2017-04-20 32 views
0

我正在嘗試爲每個方面(按性別)基於exercise = 0或exercise = 1創建兩個不同的行。第一個代碼沒有facet_wrap,基於性別的兩行代碼是不同的。第二個代碼是facet_wrap,兩行似乎是同一行。我怎樣才能改變代碼,使兩條線在每個方面都有所不同?如何根據每個方面的因子創建兩個不同的迴歸線? R,ggplot2

ggplot(cdc, aes(weight,wtdesire, color = exercise, group = 
interaction(gender,exercise))) + geom_point(alpha = 1/5) + 
geom_smooth(method = lm, aes(linetype=exercise)) 

生產:facet

然而,當我添加facet_wrap兩條線每個面似乎是相同的。

ggplot(cdc, aes(weight,wtdesire, color = exercise, group = 
interaction(gender,exercise))) + geom_point(alpha = 1/5) + 
geom_smooth(method = lm, aes(linetype=exercise)) + facet_wrap(~gender) 

生產:second

+0

你可能需要在第二個情節只使用'組=鍛鍊'。 – lbusett

+0

@LoBu我也試過,但它沒有改變任何東西... –

回答

0

@LoBu溶液是正確的。下面是一個例子使用mtcars數據:

ggplot(mtcars, aes(hp, mpg, group=interaction(vs, am))) + 
     geom_point(alpha = 0.2) + 
     geom_smooth(method = lm, aes(linetype=as.factor(vs))) 

enter image description here

ggplot(mtcars, aes(hp, mpg, group=vs)) + 
     geom_point(alpha = 0.5) + 
     geom_smooth(method = lm, aes(linetype=as.factor(vs))) + 
     facet_wrap(~am) 

enter image description here

+0

謝謝!我通過as.factor而不是連續變量進行了分組。 –

相關問題