How to use multiple variables with geom_smooth in ggplot2 in r

Viewed 926

Just like the title, I want to use multiple independent variables in my model.

There is an easy example:

If I want to see the relationship between mpg and disp, I could use this:

mtcars %>% ggplot(aes(y = mpg, x = disp)) +
  geom_point() + 
  geom_smooth(formula = y ~ x)

Then I want to see the relationship between mpg and disp adjusted hp, I write the below code occurring an error:

mtcars %>% ggplot(aes(y = mpg, x = disp)) +
  geom_point() + 
  geom_smooth(formula = y ~ x + hp)

# Computation failed in `stat_smooth()`:
# object 'hp' not found 

Maybe I didn't mapping hp in ggplot(aes()), and I tried this but the same error occurring:

mtcars %>% ggplot(aes(y = mpg, x = disp, z = hp)) +
  geom_point() + 
  geom_smooth(formula = y ~ x + z)

Any help will be highly appreciated!

1 Answers

You can try to add color or size in aes()

mtcars %>% ggplot(aes(y = mpg, x = disp, color=hp)) +
  geom_point() + 
  geom_smooth(formula = y ~ x)

Yielding

enter image description here

mtcars %>% ggplot(aes(y = mpg, x = disp, color=hp, size=hp)) +
  geom_point() + 
  geom_smooth(formula = y ~ x)

enter image description here

Related