Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between setting aes in ggplot function or in a geom?

Tags:

r

ggplot2

I wonder how it's working to set aesthetics in ggplot. How it's possible to know where to put the aes in ggplot?

Consider this code:

p<- ggplot(mtcars, aes(wt, mpg, colour = "red"))
# A basic scatter plot
hello =p + geom_point(size = 4)
hello
goodbye=p + geom_point(aes(colour = factor(cyl)), size = 4)
goodbye

Here, it's possible to see that the colour red is applied to the points in the first graph (hello), and in the second (goodbye) it's getting the colour from a column. But what's the difference?

like image 424
M. Beausoleil Avatar asked Dec 10 '22 19:12

M. Beausoleil


1 Answers

The difference is that when the aes are set in the original ggplot, they are inherited by any other geom's that build on top of it. If you specify the aes only in a geom, it will only be used in that geom. If you use any specific aes in geom, they override the settings in ggplot.

In your example code, in the first instance:

p + geom_point(size = 4)

The size of the points is set to 4, and the aes(wt, mp, colour = 'red') is inherited from ggplot. In the second case:

p + geom_point(aes(colour = factor(cyl))

The resulting aes is aes(wt, mpg, colour = factor(cyl) as the wt and mpg are inherited from the ggplot object, and the colour = factor(cyl) overwrites the colour = 'red'.

like image 153
Paul Hiemstra Avatar answered May 24 '23 07:05

Paul Hiemstra