Search code examples
rggplot2pipe

Is there a base pipe way of using the unique value of a column to pipe into labs from ggplot


The problem is fairly simple - if I take a df and perform a few filtering steps on it, I'd like to be able to pipe the output of those into a ggplot function and use the unique value of a particular column as the title. Works with the magrittr pipe and curly braces:

starwars %>% 
  filter(hair_color == "blond") %>%
  {
    ggplot(data = ., aes(x = height, y = mass, col = birth_year)) +
      geom_point() +
      labs(title = unique(.$species))
  }

Doesn't work with the base pipe equivalent:

starwars |> 
  filter(hair_color == "blond") |> 
  {
    ggplot(data = _, aes(x = height, y = mass, col = birth_year)) +
      geom_point() +
      labs(title = unique(.$species))
  }

Error in { : 
  function '{' not supported in RHS call of a pipe (<input>:3:7)

Other than assigning the df before calling ggplot, are there any other options?


Solution

  • I think this works:

    library(dplyr)
    library(ggplot2)
    starwars |> 
      filter(hair_color == "blond") |>
      { \(x)
      ggplot(data = x, aes(x = height, y = mass, col = birth_year)) +
      geom_point() +
      labs(title = unique(x$species)) }() 
    

    Please have a look at this. Also, look here. The frequently discussed error message:

    Error in { : function '{' not supported in RHS call of a pipe (:3:3)

    You might also like to try:

    Sys.setenv(`_R_USE_PIPEBIND_` = TRUE) 
    starwars |> 
      filter(hair_color == "blond") |>
      . => { 
        ggplot(data = ., aes(x = height, y = mass, col = birth_year)) +
          geom_point() +
          labs(title = unique(.$species)) }