Reputation: 53
I have a plot with two sets of data. I was wondering if someone could help me print lines of best fit? Here is my current code. I am trying to use data I created that I'm calling gender_data:
#Insert Data
library(readxl)
gender_data <- read_excel("Desktop/gender_data.xlsx")
View(gender_data)
#Matrix
times_df <- data.frame(gender_data)
print(gender_data)
#Data Set
plot(x = gender_data$ "Olympic year",
y = gender_data$ "Men's winning time (s)",
xlab = "year",
ylab = "winning times",
ylim = c(7,13),
col = "green",
pch = "*")
points(x = gender_data$ "Olympic year",
y = gender_data$ "Women's winning time (s)",
col = "blue", pch = "`")
dput(head(gender_data))
My console is spitting out:
#dput(head(gender_data))
structure(list(`Olympic year` = c(1900, 1904, 1908, 1912, 1916,
1920), `Men's winning time (s)` = c(11, 11, 10.8, 10.8, NA, 10.8
), `Women's winning time (s)` = c(NA_real_, NA_real_, NA_real_,
NA_real_, NA_real_, NA_real_)), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"))
Upvotes: 0
Views: 870
Reputation: 571
As you have not provided the data you used and did not include what kind of model you would like to fit, here is example code using the mtcars
data. The fit is done using a linear model lm()
.
model_mpg_disp <- lm(mpg ~ disp, data = mtcars)
model_mpg_disp_predictions <- predict(model_mpg_disp)
plot(mtcars$disp, mtcars$mpg)
lines(mtcars$disp , model_mpg_disp_predictions)
For an ggplot()
way as asked by @hachiko, we can use geom_smooth()
:
library(tidyverse)
ggplot(data = mtcars,
aes(x = disp, y = mpg)) +
geom_point() +
geom_smooth(method = "lm")
Upvotes: 1