2012-09-14 40 views
0

我試圖用ggplot2創建變量之間的線性相關關係圖:ggplot創建相關圖

dput(sum) 
structure(list(Date = structure(c(15218, 15248, 15279, 15309, 
15340, 15371, 15400, 15431, 15461, 15492, 15522, 15553), class = "Date"), 
    Teams = c(87, 142, 173, 85, 76, 76, 93, 49, 169, 139, 60, 
    120), Scores = c("67101651", "62214988", "63183320", "66750198", 
    "61483322", "67546775", "75290893", "60713372", "77879142", 
    "70290302", "83201853", "83837301")), .Names = c("Date", 
"Teams", "Scores"), row.names = c(NA, 12L), class = "data.frame") 

這是我的命令:

ggplot(sum, aes(x = Scores, y = Teams, group=1)) + 
    geom_smooth(method = "lm", se=TRUE, size=2, formula = lm(Teams ~ Scores)) 

我得到這個錯誤:

Error in eval(expr, envir, enclos) : object 'Teams' not found 

有什麼想法?

回答

1

如果要爲例如線性模型指定公式,請使用y ~ poly(x, 1)。你並不需要,只要你想要一個簡單的線性迴歸改變formula參數(它是method = "lm"默認):

ggplot(sum, aes(x = Scores, y = Teams, group = 1)) + 
    geom_smooth(method = "lm", formula = y ~ poly(x, 1), se = TRUE, size = 2) 

我也建議使用Scores爲數值(as.numeric(Scores))如果你不」 t想要這個變量是分類的。這將改變回歸線。

Score作爲範疇變量:

categorial

Score作爲數值變量:

numeric

+0

有一種簡單的方式來打印第r平方值作爲圖例? – user1471980

+0

一個簡單的方法是將其打印在標題中。只需添加'opts(title = bquote(R^2〜「:」〜。(summary(lm(Teams〜as.numeric(Scores),sum))$ r.squared)))'到plot。 –