ggplot2 中的美学和 bang-bang

Aesthetics and bang-bang in ggplot2

我正在尝试编写一个创建条形图的函数,但我无法获得正确的 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)
}

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")

您在找这样的东西吗?

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 创建