使用为绘图创建的函数时 facet_grid() 出错

Error with facet_grid() when using a function created for plotting

我创建了一个用于在 R 中返回绘图的函数。 facet_grid() 似乎有一个问题,在使用创建的绘图函数绘图时出现,但在不使用该函数时不会出现(即使我使用完全相同的代码行)。

# function for plotting
barplot_fill <- function(dataset, x, y, fill, jaar) {
  p <- ggplot(dataset, aes(x=x, y=y, fill=fill)) +
    geom_bar(stat = "identity") +
    facet_grid(~ jaar) +
    theme_bw() + 
    scale_y_continuous(labels=comma)

  return(p)
}

我想绘制以下数据框中的变量:

df <- data.frame(V1=c(1,2,3,4), V2=c(20,25,46,13), V3=c('a','a','b','b'), V4=c(2018,2019,2018,2017))

调用函数时,出现以下错误:

barplot_fill(df, V1, V2, V3, V4)

Error: At least one layer must contain all faceting variables: dataset$jaar. * Plot is missing dataset$jaar * Layer 1 is missing dataset$jaar

当我不调用创建的函数而只​​是使用 ggplot 代码行创建绘图时,R 会创建绘图并且不会出现错误。

ggplot(df, aes(x=V1, y=V2, fill=V3)) +
  geom_bar(stat = "identity") +
  theme_bw() + 
  facet_grid(~ V4) +
  scale_y_continuous(labels=comma)

我不明白为什么它在创建的函数中给我一个错误,以及为什么当 运行 完全相同的代码行不使用该函数时错误没有出现。谁能解释一下为什么在调用创建的函数时出现错误?

问题是 jaar 未在 facet_grid 调用中求值,但 ggplot 正在您提供的数据集中寻找 jaar 列。实际上,如果删除函数的 fact_grid 部分,在 ggplot 调用 xyfill 时会发生类似的事情:

barplot_fill_no_facet <- function(dataset, x, y, fill, jaar) {
  p <- ggplot(dataset, aes(x = x, y = y, fill = fill)) +
    geom_bar(stat = "identity") +
    theme_bw() +
    scale_y_continuous()

  return(p)
}

barplot_fill_no_facet(df, V1, V2, V3, V4)

Error in FUN(X[[i]], ...) : object 'V1' not found

一个解决方案使用 aes_stringformula 作为 facet_grid

barplot_fill <- function(dataset, x, y, fill, jaar) {
  p <- ggplot(dataset, aes_string(x = x, y = y, fill = fill)) +
    geom_bar(stat = "identity") +
    facet_grid(formula(paste("~", jaar))) +
    theme_bw() +
    scale_y_continuous()

  return(p)
}

barplot_fill(df, "V1", "V2", "V3", "V4") 

除了 scale_y_continuous 的小故障(您尚未定义 comma)之外,问题在于对变量的评估。对于 aes,您可以使用 aes_string 并传递字符串,但 facet_grid 具有不同的格式。请参阅可变方面 here

barplot_fill <- function(dataset, x, y, fill, jaar) {

  jaar <- enquo(jaar)

  p <- ggplot(dataset, aes_string(x=x, y=y, fill=fill)) +
    geom_bar(stat = "identity") +
    facet_grid(cols = vars(!!jaar)) +
    theme_bw()

  return(p)
}

df <- data.frame(V1=c(1,2,3,4), V2=c(20,25,46,13), V3=c('a','a','b','b'), V4=c(2018,2019,2018,2017))


barplot_fill(df, "V1", "V2", "V3", V4)