Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: how to assign value of variable to ggplot title

Tags:

r

ggplot2

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)

like image 303
zoowalk Avatar asked Apr 23 '20 20:04

zoowalk


1 Answers

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

enter image description here

like image 103
akrun Avatar answered Oct 19 '22 22:10

akrun