【问题标题】:ggplot handling quoted variableggplot 处理引用变量
【发布时间】:2016-01-16 12:43:18
【问题描述】:

在对数据框执行操作后生成ggplot() 图时遇到了意外问题。我提供了一个说明性示例:

func <- function(){  
library(ggplot2)
df <- read.table(....)
# perform operation on df to retrieve column of interest index/number
column.index <- regexpr(...)   
# now need to find variable name for this column
var.name <- names(df)[column.index]
# also need to mutate data in this column
df[,column.index] <- df[,column.index] * 10
# generate plot
plot <- ggplot(data, aes(x=var.name))+geom_bar()
print(plot)
}

这里 ggplot 会抛出一个错误,因为 var.name 被引用,例如,“mpg”。 知道如何解决这个问题吗?

编辑:来自this question 的测试解决方案无济于事。

【问题讨论】:

  • @David:我在 NSE 中测试了quote,所以我添加了标签以提示问题的性质。
  • 明白了。快速打字和思考,我想我说的:-)

标签: r ggplot2 dataframe quotes quoting


【解决方案1】:

使用aes_string,它允许您为变量传递一个字符串名称。

【讨论】:

  • @smci:感谢您的建议。 aes_string 仅在 var.name 从引号中删除时才有效:即:var = as.name(var.name)
【解决方案2】:

您可以使用包“dplyr”将 var.name 列重命名为通用名称 (x),然后在 x 上绘图:

# also need to mutate data in this column
df[,column.index] <- df[,column.index] * 10
# ***NEW*** re-name column to generic name
df <- rename_(df, .dots=setNames(list(var.name), 'x'))
# generate plot
plot <- ggplot(df, aes(x=x))+geom_bar()

【讨论】:

  • 然后在绘图调用末尾添加+xlab(var.name) 以重命名轴
  • 更简单的重命名步骤df &lt;- rename_(df, x = var.name)
  • 这是一个黑客;使用aes_string(),这就是它的用途
猜你喜欢
  • 2016-06-17
  • 1970-01-01
  • 2016-07-31
  • 1970-01-01
  • 1970-01-01
  • 2021-07-03
  • 2015-07-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多