Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with abline()

Tags:

r

ggplot2

OK, so I've tried every possible combination after Googling any other way to get a line of best fit on my graph (that only has 2 data points).

I have imported my data set Seal_Tide_data_set from Excel. The code for the plot works until I try to add a trendline, and yes I've added the trend line code to the existing plot code so they are on the same lines - also tried without and keep getting error message "plot.new has not been called yet"

Here is my code(without trend line):

Seal_Tide_data_set
library(ggplot2)
ggplot(Seal_Tide_data_set,aes(time,numSeals)) + 
    geom_point() + 
    labs(x="Number of Seals",y="Time of Day") + ylim(0,14)

This works and gets me to a graph, now I just need to add a line of best fit, so what I know so far is that the abline() function is best

I have tried:

Seal_Tide_data_set
library(ggplot2)
ggplot(Seal_Tide_data_set,aes(time,numSeals)) + 
   geom_point() + labs(x="Number of Seals",y="Time of Day") + 
   ylim(0,14) + 
   abline(lm(Seal_Tide_data_set$time~Seal_Tide_data_set$numSeals))

and get this error code:

Error in int_abline(a = a, b = b, h = h, v = v, untf = untf, ...) : 
  plot.new has not been called yet

I have also tried:(which i really didn't expect to work because r doesn't know what plot i am referring to with the abline function)

Seal_Tide_data_set
library(ggplot2)
ggplot(Seal_Tide_data_set,aes(time,numSeals)) + 
 geom_point() + labs(x="Number of Seals",y="Time of Day") + 
 ylim(0,14) 
abline(lm(Seal_Tide_data_set$time~Seal_Tide_data_set$numSeals))

Really not sure what else to try (I've also tried other line functions like lines() and so on with the two formats above replaced with abline())

any help is greatly appreciated! (:

like image 960
Genevieve Rice Avatar asked Dec 20 '25 09:12

Genevieve Rice


1 Answers

Try adding + geom_smooth(method="lm") to your ggplot2 specification.

abline() is designed for base plots, and just doesn't work with ggplot2.

like image 110
Ben Bolker Avatar answered Dec 22 '25 00:12

Ben Bolker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!