What is the difference between

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


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

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)

Add histogram geom:

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

Reuse ggplot object with different geom:

p + geom_point(aes(cyl, mpg))

This is a simple example but you can understand that when creating more complicated visualizations, the ability to reuse plot objects comes in handy.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.