代码之家  ›  专栏  ›  技术社区  ›  zoowalk

ggplot2:如何将变量的值指定给ggplot title

  •  0
  • zoowalk  · 技术社区  · 4 年前

    在“一次性”过滤基础数据帧之后,如何将变量的值分配给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
    

    于2020年4月23日由 reprex package (v0.3.0)

    1 回复  |  直到 4 年前
        1
  •  6
  •   akrun    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