2012-03-12 221 views
-1

可能重複:
ggplot2: Adding Regression Line Equation and R2 on graph與GGPLOT2計算相關係數R中

我用下面的程序來繪製與迴歸線的散點圖。但我也想計算相關係數。我怎樣才能得到它與ggplot2?我怎樣才能在散點圖上添加回歸直線方程和相關係數(R)?

library(ggplot2) 
d <- data.frame(x=c (1.0325477, 0.6746901, 1.0845737, 1.1123872, 1.1060822, 0.8595918, 0.8512941, 1.0148842, 1.0722369, 0.9019220 , 0.8809147, 1.0358256, 0.9903858, 1.0715174 , 1.1034405, 1.0143966,0.9802365, 0.7177169 , 0.9190783, 0.8408701) , 
    y= c (0.8550177, 0.8352162 ,1.0236998, 1.1071665, 0.6768144, 0.8449983 ,0.7616483, 0.8259199, 1.1539598, 1.4125006, 1.0511816, 0.9366184, 1.4101268, 1.2937913, 1.4147219 ,1.2943105 ,0.7859749, 0.6689330, 0.6940164, 0.8093392), names = c("A","C","E","D","G","F","I","H","K","M","L","N","Q","P","S","R","T","W","V","Y")) 
ggplot(d, aes(x,y)) + geom_point(shape=1)+geom_smooth(method=lm, se=FALSE, fullrange=T)+geom_text(aes(label=names ,hjust=0)) 

請幫幫我。

+4

計算相關性的R函數是cor()。當你不知道函數的名字時尋求幫助,總會有'library(sos); findFn( 「相關」)' – Andrie 2012-03-12 09:26:21

回答

1

計算相關係數和線性迴歸的正常方法是在ggplot外部。在ggplot2的引擎蓋下調用lm,至少在method = lm時。解決您的問題的方法是混合使用lm,corgeom_text。 @joran在評論中提到的帖子提供了一些很好的提示。