0

Can someone please help me understand why the first line of code works, but not the second? I'm relatively new to R and would appreciate any help I can get!

ggplot(penguins, aes(x = flipper_length_mm, y = body_mass_g)) + geom_point() + geom_smooth(method=lm, se=FALSE)

ggplot(penguins) + geom_point(mapping = aes(x=flipper_length_mm, y = body_mass_g)) + geom_smooth(method=lm, se=FALSE)

for more context, I get the following error for the second line: Error in geom_smooth(): ! Problem while computing stat. ℹ Error occurred in the 2nd layer. Caused by error in compute_layer(): ! stat_smooth() requires the following missing aesthetics: x and y Run rlang::last_error() to see where the error occurred.

Meetch
  • 3
  • 1
  • 1
    The mapping for each layer (i.e. the stuff inside each `aes` call) is by default inherited from the initial `ggplot()` call. Using `aes` inside one layer (e.g. inside the `geom_point` call) only affects that layer. So in your first version, both the geom_point and geom_smooth layers correctly inherit their x and y aesthetics from the plot object. In the second version, geom_smooth has no x or y aesthetics defined because there is no mapping to inherit - it can't inherit from the geom_point layer. – Allan Cameron Feb 12 '23 at 11:44

1 Answers1

0

Please always use a minimum reproducible example when posting a question. You should include require('ggplot2') and require('palmerpenguins')

The ggplot2 vignette explicitly says:

mapping

Default list of aesthetic mappings to use for plot. If not specified, must be supplied in each layer added to the plot.

In your second alternative, you supply the mapping argument for the geom_point() layer but not for the geom_smooth() layer.

Therefore the following block of code will work:

ggplot(penguins) + geom_point(mapping = aes(x=flipper_length_mm, y = body_mass_g)) + geom_smooth(mapping = aes(x=flipper_length_mm, y = body_mass_g), method=lm, se=FALSE)
Pedro Schuller
  • 280
  • 1
  • 12