0

I have a large dataset (n>1000) of environmental data over time. With the use of ggplot I create a figure in R, and with the use of geom_smooth I applied a simple linear model to have an idea about the magnitude of the trend. With a different method I already found a significant trend.

I have used the function stat_poly_eq as described in Add regression line equation and R^2 on graph by @Pedro Aphalo to retrieve the formula of the trendline, but I do not agree on the result. If I apply x=1980 and x=2020 to the suggested formula, the results (y=0.1776 and y=0.1775) do not (visually) agree with the computed trendline. By checking the line I expected it to be more around y=0.18 and y=0.15.

What might be going wrong here?

library(ggplot)
library(ggpmisc)
ggplot(df, aes(x=Date, y=NDVI))+
  geom_point()+
  geom_smooth(method="lm", formula= y~x)+
  stat_poly_eq(formula= y~x, 
      aes(label=paste(..eq.label.., ..rr.label.., sep="~~~")),
      parse=TRUE)

enter image description here

S Verhoef
  • 91
  • 1
  • 2
  • 11
  • I think it is easier to do it the other way around. That is perform your calculation outside of ggplot2 and then just plot the result. – G. Grothendieck Jan 15 '21 at 12:47
  • You did not post your data so hard to be sure, but I suspect that the date column is coerced to a number by some logic that is internal to lm() function. As a result, your x values used to calculate the trendline probably do not start from 1, but from some number that is much bigger than 1. That would explain the coefficient of 10^-6. – Otto Kässi Jan 15 '21 at 12:49
  • @OttoKässi You mean that the geom_smooth with the lm gives a wrong result (and so the printed trendline), and the stat_poly_eq represents a more accurate trendline? – S Verhoef Jan 15 '21 at 13:57
  • stat_poly_eq probably builds on lm(). I believe that your issue is caused by the fact that your x-variable is a date. – Otto Kässi Jan 15 '21 at 14:01
  • if you edit your question to make it a reproducible example (https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example), you would get better responses – Otto Kässi Jan 15 '21 at 14:19

0 Answers0