difference between the two ways of using aes in ggplot?

后端 未结 1 1028
情深已故
情深已故 2021-01-28 00:36

I recently started learning R but am confused with the aes feature in ggplot2.

I have seen two different places where aes is placed in the code.

ggplot(         


        
1条回答
  •  粉色の甜心
    2021-01-28 01:24

    Can't find a dupe, so here's an answer:

    Aesthetics specified in ggplot() are inherited by subsequent layers. Aesthetics specified in particular layers are specific only to that layer. Here's an example:

    library(ggplot2)
    
    ggplot(mtcars, aes(wt, mpg)) +
      geom_point() + 
      geom_smooth()
    
    ggplot(mtcars) +
      geom_point(aes(wt, mpg)) + 
      geom_smooth()  # error, geom_smooth needs its own aesthetics
    

    This is mostly useful when you want different layers to have different specifications, for example these two plots are different, you have to decide which you want:

    ggplot(mtcars, aes(wt, mpg, color = factor(cyl))) +
      geom_point() + 
      geom_smooth()
    
    ggplot(mtcars, aes(wt, mpg)) +
      geom_point(aes(color = factor(cyl))) + 
      geom_smooth()
    

    On individual layers, you can use inherit.aes = FALSE to turn off inheritance for that layer. This is very useful if most of your layers use the same aesthetics, but a few do not.

    0 讨论(0)
提交回复
热议问题