【问题标题】:pipe ggplot2 w/ dynamic title带有动态标题的管道ggplot2
【发布时间】:2021-02-08 17:30:49
【问题描述】:

我可以在 ggplot 中获取数据并使用管道制作标题吗?

假设我有这样的数据,

x <- c(5,17,31,9,17,10,30,28,16,29,14,34)
y <- c(1,2,3,4,5,6,7,8,9,10,11,12)
day <- c(1,2,3,4,5,6,7,8,9,10,11,12)

df2 <- reshape2::melt(df1, id.vars='day') %>% data.frame(x, y, day, company = 'inc. company name ')

df2 %>% ggplot(aes(x=day, y=value, fill=variable), xlab="Age Group") + 
  geom_bar(stat = "identity", position = "dodge", width = 0.5) 

但是我想做这样的事情

df2 %>% ggplot(aes(x=day, y=value, fill=variable), xlab="Age Group") + 
  geom_bar(stat = "identity", position = "dodge", width = 0.5) +
  + labs(title = paste0(.$company, "numbers")) # NOT WOKRING CODE

要做到这一点,

【问题讨论】:

    标签: r ggplot2 pipe


    【解决方案1】:

    您可以在单个表达式中隔离整个 ggplot2 位,这允许您在整个 ggplot2 调用中使用 . 代词。除了节省 2 次击键之外,我不明白您为什么要这样做,但您可以。

    library(tidyverse)
    
    x <- c(5,17,31,9,17,10,30,28,16,29,14,34)
    y <- c(1,2,3,4,5,6,7,8,9,10,11,12)
    day <- c(1,2,3,4,5,6,7,8,9,10,11,12)
    
    df1 <- data.frame(x = x, y = y, day = day)
    
    df2 <- reshape2::melt(df1, id.vars='day') %>% data.frame(x, y, day, company = 'inc. company name ')
    
    df2 %>% {
      ggplot(., aes(x=day, y=value, fill=variable), xlab="Age Group") + 
        geom_bar(stat = "identity", position = "dodge", width = 0.5) +
        labs(title = paste0(.$company, "numbers"))
    }
    

    reprex package (v1.0.0) 于 2021-02-08 创建

    【讨论】:

      【解决方案2】:

      我们可以使用

       df2 %>% ggplot(aes(x=day, y=value, fill=variable), xlab="Age Group") + 
         geom_bar(stat = "identity", position = "dodge", width = 0.5) +
          labs(title = paste0(first(df2$company), "numbers"))
      

      -输出

      【讨论】:

      • 感谢您回答我的问题!然而,我正在寻找一种利用管道的解决方案,这样我就不必重述df2。使用上述解决方案,我会写出经典的df2$...,这就是我希望使用pipe 来解决的问题。
      猜你喜欢
      • 2015-05-21
      • 1970-01-01
      • 2019-10-04
      • 2019-05-20
      • 1970-01-01
      • 2020-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多