How can I assign the value of a variable to a ggplot title after filtering the underlying dataframe 'in one go'.
library(tidyverse)
#THIS WORKS
d <- mtcars %>% 
  filter(carb==4)
d %>% 
  ggplot()+
  labs(title=paste(unique(d$carb)))+
  geom_bar(aes(x=am,
               fill=gear),
           stat="count")

#THIS DOESN'T WORK
mtcars %>% 
  filter(carb==4) %>% 
  ggplot()+
  labs(title=paste(data=. %>% distinct(carb) %>% pull()))+
  geom_bar(aes(x=am,
               fill=gear),
           stat="count")
#> Error in as.vector(x, "character"): cannot coerce type 'closure' to vector of type 'character'
#THIS ALSO DOESN'T WORK
mtcars %>% 
  filter(carb==3) %>% 
  ggplot()+
  labs(title=paste(.$carb))+
  geom_bar(aes(x=am,
               fill=gear),
           stat="count")
#> Error in paste(.$carb): object '.' not found
Created on 2020-04-23 by the reprex package (v0.3.0)
We can wrap the code block with {} and use .$
library(dplyr)
library(ggplot2)
mtcars %>% 
  filter(carb==4) %>% {
  ggplot(., aes(x = am, fill = gear)) +
       geom_bar(stat = 'count') +
       labs(title = unique(.$carb))
   }
-output

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With