1

My plot:

plot(airbnb$distance_center,airbnb$price,pch=13,xlab="distance_center",ylab="price",bty="n")
mod <- lm(price~number_people+distance_center)

Now I want to include regression lines that show the correlation of price & distance_center - including all 6 characteristics of my variable "number_people"

My idea:

abline(mod$coeff[1],mod$coeff[2],lwd=2)
abline(mod$coeff[2],mod$coeff[2],lwd=2)
abline(mod$coeff[3],mod$coeff[2],lwd=2)

The Plot

Unfortunately, I don't think this is quite right, I am not sure how to make a right step. Any idea?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
jfnotk
  • 15
  • 6

1 Answers1

1

You didn't post your data, so it's difficult to tell exactly how it's structured (is "number_people" numeric or factor?). In either case, you will need one regression line for each unique number_people.

Here I have created a similar data set with the same names as yours:

mod <- lm(price ~ number_people + distance_center, data = airbnb)

plot(airbnb$distance_center, airbnb$price,
     pch = 13, xlab = "distance_center", ylab = "price", bty = "n")

invisible(sapply(unique(airbnb$number_people), function(x) {
  abline(a = coef(mod)[1] + x * coef(mod)[2], b = coef(mod)[3])
}))


Made up data

set.seed(1)

airbnb <- data.frame(
  distance_center = sqrt(runif(100, 0, 10)^2 + runif(100, 0, 10)^2),
  number_people = sample(6, 100, TRUE))
  
airbnb$price <- 50 + airbnb$number_people * 
                50 / airbnb$distance_center + rnorm(100, 0, 5)^2

Created on 2022-05-28 by the reprex package (v2.0.1)

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • number_of_people is the number of people in the airbnb and ranges from 1-6, thank you for your answer. Is there a way to simplify the ablines? Similiar to this: abline(mod$coeff[1], mod$coeff[2], lwd=2) but for 1-6 – jfnotk May 28 '22 at 14:41
  • `abline` is not vectorized, so you need to call it 6 times to get 6 regression lines. You can either do this in a loop, or inside `sapply`. Because you have two predictor variables, your model requires a line for each unique `number_people` to fully display your model. – Allan Cameron May 28 '22 at 14:46
  • May I ask how to do this in a loop? – jfnotk May 28 '22 at 15:28
  • ahh I have it figured out, thank you ser! – jfnotk May 28 '22 at 15:44