1

I have a series of csv files that I am plotting a 3rd order polynomial regression per csv file.

I set the directory and all .csv files within that directory:

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

I then iterate through the files and plot volume against time with a 3rd order polynomial 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)))}

Thus, giving

enter image description here

I now wish to add the formula of the lm function I have plotted on the graph with the r2 value.

From this SO question, I tried:

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))}

However, as you can see from the output, the label is not a 3rd order polynomial

enter image description here

Community
  • 1
  • 1
LearningSlowly
  • 8,641
  • 19
  • 55
  • 78

1 Answers1

3

You can use function stat_poly_eq() from the package ggpmisc to add equation of third order polynomial to your plot.

This example is taken from the vignette of this package.

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

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201