0
votes

Evening all, hoping someone can help. I've spent the evening messing around with the ggplot package, but for some reason, I cannot get a regression line to show up using geom_smooth!

I've included the code here, unfortunately, the terminal doesn't actually flag it as an error however which is part of the reason why I'm stumped! I've run it line by line and each line executes with no flags. The graph itself even appears without a hitch, just missing the regression line!

code:

library(ggplot2)
ScatterPlot <- ggplot(graph, aes (x= Specimen.date, y= Daily.lab.confirmed.cases)) + geom_point() + geom_smooth(method = lm) + theme(axis.text.x = element_text(angle=90))

ScatterPlot + ylim(0,5000) + labs(x = "Date") + labs(y = "Daily Cases")

output:

> ScatterPlot <- ggplot(graph, aes (x= Specimen.date, y= Daily.lab.confirmed.cases)) + geom_point() + geom_smooth(method = lm) + theme(axis.text.x = element_text(angle=90))
> ScatterPlot + ylim(0,5000) + labs(x = "Date") + labs(y = "Daily Cases")

geom_smooth() using formula 'y ~ x'

I've also tried converting columns to numeric but that didn't seem to work either ( x = as.numeric(), y = as.numeric().

any suggestions!?

Thank you

Michael

1
Try method = "lm" instead of method = lmAllan Cameron
No joy i'm afraid, thanks though!Michael_V
Tricky! If geom_smooth isn't working, you could try plotting the lm directly - see example by jim89 here: community.rstudio.com/t/insert-regression-model-into-ggplot2/… Good luck!!mlcyo
please add sample data of graph.nikn8
did you try geom_smooth(method = lm, formula = y~x, se = FALSE)Mohanasundaram

1 Answers

0
votes

Alright, we got there in the end. Mlcyo (See comments, Thanks!) got most of the way. Gave me a more helpful error at least. Heres how it was amended...:

graph[] <- lapply(graph, as.numeric) # Force entire dataframe into numeric type


fit <- lm(Daily.lab.confirmed.cases ~ Specimen.date, data = graph) # Manually generate linear model 

 geom_line(data = fortify(fit), aes(x = Specimen.date, y = .fitted)) # Insert after geom_point()

Hope it helps someone else! Thanks again mlcyo, good luck with the PhD!

M