1
votes

scatterplot

abundance = data.frame(lncount = c(13, 865, 1800), lnedna = c(4.72, 5.05,   5.22,   5.24,
                                                         5.36,  5.71,   5.63,   5.97,
                                                         6.08,  6.20,   6.43,   6.54))
xyplot(lnedna ~ lncount, data = abundance, 
   xlab = "Mussel Count by Snorkel Survey",
   ylab = "eDNA concentraion (gene sequence/Liter) on log scale", 
   main = "Mussel Abundance")

Add fit lines

abline(lm(lnedna ~ lncount))

This is the error I keep getting when trying to add the regression line: Error in eval(expr, envir, enclos) : object 'lnedna' not found

lnedna is working fine for making the scatter plot, why is it not working to add the regression line?

2
Pass the data to the lm function: lm(lnedna ~ lncount, data=abundance) - storaged
On a sidenote, must you use xyplot()? - InfiniteFlash
Why not plot()? - InfiniteFlash
@storaged and @ InfiniteFlashChess I also tried your suggestions #Add fit lines abline(lm(lnedna ~ lncount, data = abundance)) but then I get this error: Error in int_abline(a = a, b = b, h = h, v = v, untf = untf, ...) : plot.new has not been called yet. Further I tried just plot() and get the same error - Ellen

2 Answers

2
votes

Looks like you need to add the abline in the xyplot call:

lattice::xyplot(lnedna ~ lncount, data = abundance, 
                panel = function(x, y) {
                  lattice::panel.xyplot(x, y)
                  lattice::panel.abline(lm(y ~ x))
                },
                xlab = "Mussel Count by Snorkel Survey",
                ylab = "eDNA concentraion (gene sequence/Liter) on log scale", 
                main = "Mussel Abundance")

From this question: How to add abline with lattice xyplot function?

1
votes

I was not able to repoduce your answer using plot(). Thanks to hrabel for the lattice answer. Credit to him for that one.

ggplot2

library(ggplot2)

fit <- lm(lnedna ~ lncount, data = abundance)


ggplot(data = abundance, aes(x = lncount, y = lnedna))+
geom_point()+
geom_smooth(method = "lm", se = FALSE)+
xlab("Mussel Count by Snorkel Survey")+
ylab("eDNA concentraion (gene sequence/Liter) on log scale")+
ggtitle("Mussel Abundance")+
annotate("text" ,x = 1300, y = 6.13, label = paste("R-squared = ", summary(fit)$r.squared))

enter image description here

lattice (from hrabel below)

lattice::xyplot(lnedna ~ lncount, data = abundance, 
                panel = function(x, y) {
                  lattice::panel.xyplot(x, y)
                  lattice::panel.abline(lm(y ~ x))
                  lattice::panel.text(1300, 6.13, paste("R-squared = ", summary(fit)$r.squared), sep = "")
                },
                xlab = "Mussel Count by Snorkel Survey",
                ylab = "eDNA concentraion (gene sequence/Liter) on log scale", 
                main = "Mussel Abundance")

enter image description here