问题
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