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

时间:2020-04-23 20:36:51

标签: 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")



#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

reprex package(v0.3.0)于2020-04-23创建

1 个答案:

答案 0 :(得分:4)

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

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

-输出

enter image description here