ggplot 处理引用的变量
ggplot handling quoted variable
我 运行 在对数据帧进行操作后生成 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 的测试解决方案无济于事。
您可以使用包 "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()
使用 aes_string
,它允许您为变量传递字符串名称。
我 运行 在对数据帧进行操作后生成 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 的测试解决方案无济于事。
您可以使用包 "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()
使用 aes_string
,它允许您为变量传递字符串名称。