ggplot2:如何将变量的值分配给 ggplot 标题

zoo*_*alk 5 r ggplot2

在“一次性”过滤基础数据框后,如何将变量的值分配给 ggplot 标题。

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")
Run Code Online (Sandbox Code Playgroud)



#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
Run Code Online (Sandbox Code Playgroud)

reprex 包(v0.3.0)于 2020 年 4 月 23 日创建

akr*_*run 6

我们可以包装代码块{}并使用.$

library(dplyr)
library(ggplot2)
mtcars %>% 
  filter(carb==4) %>% {
  ggplot(., aes(x = am, fill = gear)) +
       geom_bar(stat = 'count') +
       labs(title = unique(.$carb))
   }
Run Code Online (Sandbox Code Playgroud)

-输出

在此处输入图片说明