difference between the two ways of using aes in ggplot?

谁说胖子不能爱 提交于 2021-02-17 06:21:25

问题


I recently started learning R but am confused with the aes feature in ggplot2.

I have seen two different places where aes is placed in the code.

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy))

ggplot(mpg, aes(x = displ, y = hwy)) +
  geom_point()

What is the difference between the two?


回答1:


Can't find a dupe, so here's an answer:

Aesthetics specified in ggplot() are inherited by subsequent layers. Aesthetics specified in particular layers are specific only to that layer. Here's an example:

library(ggplot2)

ggplot(mtcars, aes(wt, mpg)) +
  geom_point() + 
  geom_smooth()

ggplot(mtcars) +
  geom_point(aes(wt, mpg)) + 
  geom_smooth()  # error, geom_smooth needs its own aesthetics

This is mostly useful when you want different layers to have different specifications, for example these two plots are different, you have to decide which you want:

ggplot(mtcars, aes(wt, mpg, color = factor(cyl))) +
  geom_point() + 
  geom_smooth()

ggplot(mtcars, aes(wt, mpg)) +
  geom_point(aes(color = factor(cyl))) + 
  geom_smooth()

On individual layers, you can use inherit.aes = FALSE to turn off inheritance for that layer. This is very useful if most of your layers use the same aesthetics, but a few do not.



来源:https://stackoverflow.com/questions/55081913/difference-between-the-two-ways-of-using-aes-in-ggplot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!