ggplot2labelaestheticsggrepel

ggplot2::geom_smooth() drops aesethetics "label" with {ggrepel}


I want to use ggplot2::geom_smooth() together with the {ggrepel} package, but I always get a warning. See the following Reprex with the Anscombe dataset:

library(ggplot2)
library(ggrepel)
anscombe |>
    ggplot(
        aes(
            x = x3,
            y = y3,
            label = rownames(anscombe)
        )
    ) +
    geom_point() +
    geom_smooth(
        formula = y ~ x,
        se = FALSE,
        method = "lm"
    ) +
    geom_text_repel()
#> Warning: The following aesthetics were dropped during statistical transformation: label.
#> ℹ This can happen when ggplot fails to infer the correct grouping structure in
#>   the data.
#> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical
#>   variable into a factor?

Created on 2024-05-29 with reprex v2.1.0

How to get rid of this warning?


Solution

  • The "label" aesthetic isn't 'understood' by geom_smooth(), e.g.

    image_1.png

    So, if you insert "label" in geom_text_repel(), or if you don't pass the label aesthetic to geom_smooth(), you shouldn't get the warning:

    library(ggplot2)
    library(ggrepel)
    anscombe |>
      ggplot(
        aes(
          x = x3,
          y = y3
          )
        ) +
      geom_point() +
      geom_smooth(
        formula = y ~ x,
        se = FALSE,
        method = "lm"
        ) +
      geom_text_repel(
        aes(
          label = rownames(anscombe)
          )
        )
    

    
    anscombe |>
      ggplot(
        aes(
          x = x3,
          y = y3,
          label = rownames(anscombe)
        )
      ) +
      geom_point() +
      geom_smooth(
        aes(
          x = x3,
          y = y3
        ),
        formula = y ~ x,
        se = FALSE,
        method = "lm",
        inherit.aes = FALSE
      ) +
      geom_text_repel()
    

    Created on 2024-05-30 with reprex v2.1.0