使用R

时间:2016-04-22 07:49:32

标签: r ggplot2

我有一系列csv文件,我正在绘制每个csv文件的三阶多项式回归。

我在该目录中设置目录和所有.csv文件:

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

然后,我使用三阶多项式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))}

但是,从输出中可以看出,标签不是三阶多项式

enter image description here

1 个答案:

答案 0 :(得分:3)

您可以使用包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