0

I have this code for plotting x,y and showing the regression line and fit statistics:

for (i in unique(Data$SeasAlltxt)){
  print (i)
  subdata1 <- subset(Data, SeasAlltxt == i)
  for (j in unique(Data$ALSCIDtxtall)){
    subdata2 <- subset(subdata1, ALSCIDtxtall == j)
    plot(subdata2$PeakToGone, subdata2$NO3_AVG, xlim = c(0, 70))
    abline(fit <- lm(NO3_AVG~PeakToGone, data = subdata2))
    rmse <- round(sqrt(mean(resid(fit)^2)), 2)
    r2 <- round(summary(fit)$r.squared, 3)
    ycoord <- max(subdata2$NO3_AVG)
    eqn <- bquote(~~ r^2 == .(r2) * "," ~~ RMSE == .(rmse))
    text(40, ycoord, eqn, pos = 4)
  }
}

This works for most of plots and shows the text on the plot. However, some plots do not show the text. The axes of these plots encompass the values for the coordinates of origin (40, ycoord) for the text, so I am confused as to why the text does not appear. I tried changing these coordinates to be in the center of the plots, and the text still does not appear on the same plots.

Any thoughts?

viridius
  • 477
  • 5
  • 17
  • 1
    Have you tried setting `eqn` to some text (e.g.`eqn<-"test"`) to make sure that it is not an error with `eqn`? – John Paul Oct 24 '14 at 16:33
  • 2
    Please take the time to create a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). If we cannot re-create the problem, it will be very difficult to help you. – MrFlick Oct 24 '14 at 16:45
  • Are there `NA` values for `y` in the groups for which the text fails to plot? It might be worth adding `print(ycoord)` to the loop (and correcting this problem, if it exists, with `ycoord <- max(subdata2$NO3_AVG, na.rm=TRUE)`). Alternatively, replace your `text` call with `legend('topright', legend=eqn, bty='n')`. – jbaums Oct 24 '14 at 17:02
  • On another note, if you like you can replace your nested loops with: `sapply(split(Data, list(Data$SeasAlltxt, Data$ALSCIDtxtall)), function(x) { ... })`, where `...` is the expression you want to apply to the subset `x`. – jbaums Oct 24 '14 at 17:08
  • 1
    Yep. It was the NA values causing the problem. I replaced the `text` call with `legend('topright', legend=eqn, bty='n')`, as suggested by jbaums and it now works for all plots. Thanks. – viridius Oct 24 '14 at 17:09
  • To debug this kind of problem, it is often useful to `print`/`cat` variables after their creation in the loop. Or, if you use the `split`/`sapply` approach I suggested, you can assign the function to an object first, then `debug()` it to step through. – jbaums Oct 24 '14 at 17:11

0 Answers0