deradelo
deradelo

Reputation: 147

Is there a way to call a tidyverse created data frame inside a ggplot2 two or more times?

I'm trying to do a graph in ggplot2 and trying to highlight or differenciate one of the factor for the other ones, the next code can reproduce what I'm trying to do with a red point for Datsun 710 car:

mtcars <- mtcars %>% 
  rownames_to_column("car")

mtcars %>% 
  ggplot(aes(x = fct_reorder(car, mpg), 
             y = mpg, 
             label = mpg)) +
  geom_point(color = if_else(mtcars$car == "Datsun 710", "Red", "Black")) +
  geom_text(size = 3, hjust = -0.2) + 
  coord_flip()

But I want to do it withouth calling the df again on the eigth line: mtcars$car, and not depend on a df outside of the ggplot first df argument.

Is it possible?

Upvotes: 1

Views: 179

Answers (2)

Elin
Elin

Reputation: 6755

You could make a function that forces use of the same data frame.

library(tibble)
library(ggplot2)
library(magrittr)
library(forcats)
library(dplyr)
mtcars2 <- mtcars %>% 
  rownames_to_column("car")

foo <- function(x){
  x %>% 
  ggplot(aes(x = fct_reorder(car, mpg), 
             y = mpg, 
             label = mpg)) +
  geom_point(color = if_else(x$car == "Datsun 710", "Red", "Black")) +
  geom_text(size = 3, hjust = -0.2) + 
  coord_flip()
}

foo(mtcars2)

However note that if it is a tibble the $ notation will not work and you need to use pull().

I don't see much benefit in piping here, though.

Upvotes: 1

G. Grothendieck
G. Grothendieck

Reputation: 269556

Use dot within brace brackets:

library(dplyr)
library(forcats)
library(ggplot2)
library(tibble)

mtcars %>% 
  rownames_to_column("car") %>%
  { ggplot(., aes(x = fct_reorder(car, mpg), y = mpg, label = mpg)) +
    geom_point(color = if_else(.$car == "Datsun 710", "Red", "Black")) +
    geom_text(size = 3, hjust = -0.2) + 
    coord_flip()
  }

Upvotes: 3

Related Questions