ggplot处理引用变量

时间:2015-10-18 00:02:00

标签: r ggplot2 dataframe quotes quoting

在对数据帧执行操作后生成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的经过测试的解决方案无济于事。

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:-3)

你可以使用包&#34; dplyr&#34;将var.name列重命名为generic(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()
相关问题