Search code examples
rtrendline

Trendline does not show up in plot (baseR)


I'm trying to create a trendline on a scatterplot using baseR. I used the abline() function. Upon executing, I did not encounter an error, but the trendline does not show up in the plot. Could it be because I plotted on a logarithmic scale?

IAA_M<-c(0, 1E-3, 1E-5, 1E-7, 1E-9, 1E-11)
gem_wortels<-c(7.71, 2.275, 6.34285, 4.71666, 8.36666, 4.822222)

plot(
  IAA_M,
  gem_wortels,
  ylim = range(c(
    gem_wortels - stdev_wortels, gem_wortels + stdev_wortels
  )),
  pch = 19,
  xlab = "[IAA] (M)",
  ylab = "gemiddelde wortellengte (cm)",
  log = 'x'
)
arrows(
  IAA_M,
  gem_wortels - stdev_wortels,
  IAA_M,
  gem_wortels + stdev_wortels,
  length = 0.05,
  angle = 90,
  code = 3
)
abline(gem_wortels ~ IAA_M,
       data_wortelgroei_regressie,
       lty = 3,
       col = 'red')

Solution

  • You need to supply an lm model to abline, not just a bare formula. However, you will need to use the log10 value of your x axis on the right hand side of the formula in the model. Also, since the first value of your x axis variable is 0, the first row needs to be omitted, otherwise lm will throw an error since log10(0) is NaN.

    Your example doesn't include the vector of standard deviations, so I have made one up for demonstration purposes:

    stdev_wortels <- c(2.1, 1.2, 1.5, 1.1, 2, 1.4)
    
    abline(lm(gem_wortels[-1] ~ log10(IAA_M[-1])),
           lty = 3, 
           col = 'red')
    

    enter image description here