简体   繁体   中英

How to use multiple variables with geom_smooth in ggplot2 in r

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!

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

在此处输入图像描述

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM