Home > database >  What's the difference between placing the aes() function inside the ggplot() function or inside
What's the difference between placing the aes() function inside the ggplot() function or inside

Time:03-01

I am new to programming and coding, trying to learn R in the Google course.

They have given several examples for visuals using the ggplot functions, but they have used the aes() in two ways.

First:

ggplot(data=palmerpenguins) geom_point(mapping = aes(x = bill_length_mm,y = body_mass_g)) The aes() function is inside the geom_point() function.

Then they show: ggplot(data, aes(x=distance, y= dep_delay, color=carrier, size=air_time, shape = carrier)) geom_point()

Now the aes() function is in the ggplot() function, where they specify the dataset.

What is the reason for the switch? It seems like aes() can go in either place. Is this true? For something that is so specific like coding, it's confusing why you could do it either way. Any explanation would be appreciated. Thanks

CodePudding user response:

If you only have one layer, it really doesn't matter. Each later (geom) can have it's own set of mappings. If you add it to the ggplot() call, that's the "default" mapping that will be used if the later doesn't specify it's own. You can acually add the aes() outside the ggplot() and geom_ calls and that will also act at the default. There are all the same

ggplot(data=penguins)   
  geom_point(mapping = aes(x = bill_length_mm, y = body_mass_g))

ggplot(penguins, aes(x = bill_length_mm, y = body_mass_g))   
  geom_point()

ggplot(penguins)   
  aes(x = bill_length_mm, y = body_mass_g)   
  geom_point()

Here's an example with two different layers with different mappings

ggplot(penguins)   
  aes(x=island, y=bill_length_mm)   
  geom_boxplot()   
  geom_jitter(aes(color=sex))

Note that the color will only apply to the jitter later, not to the boxplot layer.

enter image description here

CodePudding user response:

If you define the mapping (use aes()) inside the ggplot call, you create a set of default mapping values for all the attached geoms.

If you want to apply different mappings for each geom you add, you can define them in an aes() call within the geom itself.

  • Related