【问题标题】:Aesthetics and bang-bang in ggplot2ggplot2 中的美学和爆炸
【发布时间】:2020-12-04 11:55:07
【问题描述】:

我正在尝试编写一个创建条形图的函数,但我无法获得正确的 fill 美学。

  • 如果我使用fill = !!x 会导致Quosures can only be unquoted within a quasiquotation context.
  • fill = x 导致Aesthetics must be either length 1 or the same as the data (4): fill

我的代码:

genBar <- function(data, x, y) {
  x <- enquo(x)
  y <- enquo(y)
  plot <- ggplot(data) +
    geom_bar(aes(!!x, !!y),
             stat = 'identity',
             fill = <help>) 
  return(plot)
}

【问题讨论】:

    标签: r ggplot2 plyr


    【解决方案1】:

    fill 应该在 aes 内。试试看:

    library(ggplot2)
    
    genBar <- function(data, x, y) {
      plot <- ggplot(data) +
        geom_bar(aes({{x}}, {{y}}, fill = {{x}}),
                 stat = 'identity') 
      return(plot)
    }
    
    genBar(mtcars, cyl, mpg)
    

    如果您想将列名作为字符串传递,请使用.data 代词。

    genBar <- function(data, x, y) {
      plot <- ggplot(data) +
        geom_bar(aes(.data[[x]], .data[[y]], fill = .data[[x]]),
                 stat = 'identity') 
      return(plot)
    }
    
    genBar(mtcars, "cyl", "mpg")
    

    【讨论】:

    • 好的,谢谢!
    【解决方案2】:

    你在寻找这样的东西吗?

    library(dplyr)
    library(ggplot2)
    
    genBar <- function(data, x, y) {
      x <- enquo(x)
      y <- enquo(y)
      plot <- ggplot(data) +
        geom_bar(aes(!!x, !!y, fill = !!x),
                 stat = 'identity') 
      return(plot)
    }
    
    iris %>% 
      group_by(Species) %>% 
      summarize(Size = mean(Petal.Length)) %>%
      genBar(Species, Size)
    

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

    【讨论】:

    • 我通过添加c &lt;- data %&gt;% select(!!x) col &lt;- 1:length(c[[1]]) 解决了这个问题,但这更干净
    猜你喜欢
    • 2019-02-06
    • 1970-01-01
    • 2012-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多