Add linear regression line to plots

I would like to add linear regression lines and their equation to my two plots.

Here is my code for the plots so far:
data_df$Date <- as.Date(data_df$Date)

Create a line plot for ODO over time

odo_plot <- ggplot(data_df, aes(x = Date, y = ODO)) +
geom_line() +
labs(y = "ODO (mg/l)") +
theme_minimal() +
scale_x_continuous(breaks=data_df$Date)

Create a line plot for Temperature over time

temperature_plot <- ggplot(data_df, aes(x = Date, y = Temp)) +
geom_line() +
labs(y = "Temperature °C") +
theme_minimal() +
scale_x_continuous(breaks=data_df$Date)

And this is my table with the data:
structure(list(Date = structure(c(19486, 19493, 19501, 19507,
19514, 19521), class = "Date"), ODO = c(10.1794117647059, 10.1521929824561,
9.65347222222222, 9.7942491755048, 9.0814817469419, 8.56008140350877
), Temp = c(16.3238676470588, 15.3955614035088, 17.4575297619048,
19.8056092723088, 21.3171637519113, 22.8041029005848)), row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))

I tried to add a regression line but unfortunately it messed up my whole plot and the graph with my data and the regression line were just two horizontal lines...

Would appreciate if anyone could help me out!

Consider using a scatterplot to show the data points

library(ggplot2)
d <- data.frame(Date = structure(c(
  19486, 19493, 19501, 19507,
  19514, 19521
), class = "Date"), ODO = c(
  10.1794117647059, 10.1521929824561,
  9.65347222222222, 9.7942491755048, 9.0814817469419, 8.56008140350877
), Temp = c(
  16.3238676470588, 15.3955614035088, 17.4575297619048,
  19.8056092723088, 21.3171637519113, 22.8041029005848
))

ggplot(d, aes(x = Date, y = Temp)) +
  geom_point() +
  geom_smooth(method = "lm") +
  labs(y = "Temperature °C") +
  scale_x_continuous(breaks=d$Date) +
  theme_minimal() 
#> `geom_smooth()` using formula = 'y ~ x'

Created on 2023-08-21 with reprex v2.0.2

Thank you for the reply. Is there no way to do it with a line plot? A scatter plot seems kinda unnecessary considering i only have very few data points.

Just change geom_point to geom_line; however, that's non-standard. I can't say nobody does it that way because I haven't seen how absolutely everyone does it.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.