【问题标题】:Passing quoted variable to transform function within ggplot将带引号的变量传递给ggplot中的变换函数
【发布时间】:2015-09-03 20:39:53
【问题描述】:

我正在尝试根据这个可重复的示例制作一个可重复使用的图表函数:

test=data.frame(name=c('a', 'b', 'c', 'd', 'e', 'f'), amount=c(1,7,3,11,2,1))

ggplot(transform(test, name=reorder(name, -amount)), 
  aes(x=name, y=amount)) + 
  geom_bar(stat='identity')

我遇到的问题是让 transform 函数正常工作。

此功能有效,但没有transform:

p = function(df, x, y) {
  ggplot(df, 
    aes_string(x=x, y=y)) + 
    geom_bar(stat='identity')
}

p(test, 'name', 'amount')

当我添加transform 函数时,我得到了相同的图表:

p_order = function(df, x, y) {
  ggplot(transform(df, x=reorder(x, -y)), 
  aes_string(x=x, y=y)) + 
  geom_bar(stat='identity')
}

p_order(test, 'name', 'amount')

但给出警告:Warning message: In mean.default(X[[1L]], ...) : argument is not numeric or logical: returning NA

我尝试将x=reorder(x, -y) 的不同部分包装在getevalsubstitutequote 中。我已经尝试了几个小时,并认为这是某种 promise 概念,我只是没有掌握。

【问题讨论】:

  • 看来p = function(df, x, y) transform(df, name=reorder(x, -y)) 这就是问题所在,甚至在它到达 ggplot 之前

标签: r ggplot2


【解决方案1】:

使用赋值和[[]] 而不是转换是最容易做到的:

p_order = function(df, x, y) {
  df[[x]] <- reorder(df[[x]], -df[[y]])
  ggplot(df, aes_string(x=x, y=y)) + 
      geom_bar(stat='identity')
}
p_order(test, 'name', 'amount')

如果您想使用转换,您可以将它与get 一起使用,但只能在将其分配给新列时使用(否则您将不得不开始使用do.call

p_order = function(df, x, y) {
  ggplot(transform(df, new_col = reorder(get(x), -get(y))),
      aes_string(x = "new_col", y=y)) + 
      geom_bar(stat='identity') +
      xlab(x) # to keep it looking the same
}
p_order(test, 'name', 'amount')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多