Alex Yao
Alex Yao

Reputation: 119

Difference between putting aes(x=…) in ggplot() or in geom()

What is the difference between putting aes(x=…) in ggplot() or in geom() (e.g. geom_histogram() below):

1. in ggplot():

ggplot(diamonds) + 
  geom_histogram(binwidth=500, aes(x=diamonds$price))+ 
  xlab("Diamond Price U$") + ylab("Frequency")+ 
  ggtitle("Diamond Price Distribution")

The histogram of method A goes here

2. in the geom():

ggplot(diamonds, aes(x=diamonds$price)) + 
  geom_histogram(bidwidth= 500) + 
  xlab("Price") + ylab("Frequncy") + 
  ggtitle("Diamonds Price distribution")

The histogram of method B goes here

Upvotes: 0

Views: 594

Answers (1)

Marius
Marius

Reputation: 60060

Whether you put x = price in the original ggplot() call or in a specific geom only really matters if you have multiple geoms with different mappings. The mapping you specify in the ggplot() call will be applied to all geoms, so it's often best to put the mapping in the top level like that, if only to save you having to type it out again for each individual geom. Specify mappings in the individual geoms if they only apply to that specific geom.

Also note that it should just be aes(x = price), not aes(x = diamonds$price). ggplot knows to look in the dataframe you're using as your data argument. If you pass a vector manually like diamonds$price you might mess up facetting or grouping in a more complex plot.

Upvotes: 4

Related Questions