Search code examples
rggplot2geom-point

Trying to understanding a geom_smooth error


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.


Solution

  • 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)