watchtower watchtower - 3 months ago 12
R Question

Using aesthetics with multiple layers in ggplot

I am new to ggplot. I am trying to understand how to use ggplot. I am reading Wickham's book and still trying to wrap my head around how to use aes() function.

What's the difference between these two implementations of aes():

ggplot(mpg, aes(displ, hwy, colour = class)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE) +
theme(legend.position = "none")


and

ggplot(mpg, aes(displ, hwy)) +
geom_point(aes(colour = class)) +
geom_smooth(method = "lm", se = FALSE) +
theme(legend.position = "none")


Both of them print significantly different graphs. Any help? I am really stuck.

Pj_ Pj_
Answer

In the first one you are mapping the aesthetics globally, ggplot will try to map these aesthetics to all other geom_xyz() layers.

While in the latter case, you are mapping aesethics to a specific ggplot layer (in your case geom_point())

Comments