简体   繁体   中英

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

I wonder how it's working to set aesthetics in ggplot . How it's possible to know where to put the aes ion 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?

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' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM