2016-04-22 121 views
0

我有一系列csv文件,我繪製每個csv文件的三階多項式迴歸。添加回歸方程和r2繪製在ggplot2與R

我設置的目錄和目錄中的所有文件的.csv:

setwd("tester/results") 
filenames = dir(pattern="*.csv") 

然後我通過對時間的文件和情節的體積具有3階多項式lm迭代。

for (i in 1:length(filenames)) { tmp <-read.csv(filenames[i]); print(ggplot(aes(x = Volume, y = time), data = tmp) + geom_point(aes(color = id)) + geom_smooth(aes(color = id), method= "lm", se = F, formula=y ~ poly(x, 3, raw=TRUE)))} 

因此,給予

enter image description here

我現在要添加的lm功能我已在與r2值的曲線繪製的公式。

從這個SO question,我想:

for (i in 1:length(filenames)) { tmp <-read.csv(filenames[i]); print(ggplot(aes(x = Volume, y = time_normalised), data = tmp) + geom_point(aes(color = id)) + geom_smooth(aes(color = id), method= "lm", se = F, formula=y ~ poly(x, 3, raw=TRUE)) + stat_smooth_func(geom="text",method="lm",formula=y~poly(x,3,raw=TRUE),hjust=0,parse=TRUE))} 

然而,正如你可以從輸出中看到,標籤是不是一個3階多項式

enter image description here

+1

功能'「stat_smooth_func」'是不是在GGPLOT2庫,但是應該從要點中添加或從SO問題,你提供了@kdauria答案提供的鏈接coppied。 –

+0

對!但是,問題依然存在。標籤看起來不正確 – LearningSlowly

+0

函數'「stat_smooth_func」'僅用於第一個或第二個迴歸而不是第三個。您必須修改此代碼才能使用此功能。 –

回答

2

您可以使用功能stat_poly_eq()從包ggpmisc中添加三次多項式方程到您的圖中。

本示例摘自該軟件包的the vignette

set.seed(4321) 
x <- 1:100 
y <- (x + x^2 + x^3) + rnorm(length(x), mean = 0, sd = mean(x^3)/4) 
my.data <- data.frame(x, 
         y, 
         group = c("A", "B"), 
         y2 = y * c(0.5,2), 
         block = c("a", "a", "b", "b")) 

formula <- y ~ poly(x, 3, raw = TRUE) 
ggplot(my.data, aes(x, y)) + 
     geom_point() + 
     geom_smooth(method = "lm", formula = formula) + 
     stat_poly_eq(aes(label = paste(..eq.label.., ..adj.rr.label.., sep = "~~~~")), 
        formula = formula, parse = TRUE) 

enter image description here