# ggplot aes() choice

What is the difference between

ggplot(mtcars, aes(mpg)) +
geom_histogram(aes(y = ..density..))


and

ggplot(mtcars, aes(mpg), aes(y = ..density..)) +
geom_histogram()


I know that aes() i the geom layer overrides the aes() in the data layer. But are one of the code snippets above preferable?

The difference is that when the aesthetics are set in the ggplot function, they are inherited by any other geom's that build on top of it. If you specify the aesthetics only in a geom, it will only be used in that geom. And, as you mentioned, any aesthetics used in the geom override the settings in the ggplot function.

As far as which is preferable, I think it depends on you goal with the ggplot objects. For example, if you are only creating a single plot then it doesn't really matter which method you use. However, if you plan to present multiple different visualizations of the same data, you could reuse the ggplot object and simply add different geom layers to it:

Create a reusable ggplot object:

p <- ggplot(mtcars)


p + geom_histogram( aes(mpg, ..density..))

p + geom_point(aes(cyl, mpg))