ggplot:来自没有aes_string的变量字符串的美学

时间:2015-06-03 08:48:18

标签: r ggplot2 lazy-evaluation

我的变量v包含data.frame列名称。

我现在想把它与其索引进行联系。

通常情况下,根据索引绘制列很容易:

df <- data.frame(a = c(.4, .5, .2))
ggplot(df, aes(seq_along(a), a)) + geom_point()

但就我而言,我无法弄清楚要做什么咒语:

plot_vs <- function(df, count = 2) {
    vs <- paste0('V', seq_len(count)) # 'V1', 'V2', ...
    for (v in vs) {
        # this won’t work because “v” is a string
        print(ggplot(df, aes(seq_along(v), v)) + geom_point())
        # maybe this? but it also doesn’t work (“object ‘v.s’ not found”)
        v.s <- as.symbol(v)
        print(ggplot(df, aes(seq_along(v.s), v.s)) + geom_point())
        # this doesn’t work because i use seq_along, and seq_along('V1') is 1:
        print(ggplot(df, aes_string(seq_along(v), v)) + geom_point())
    }
}
plot_vs(data.frame(V1 = 4:6, V2 = 7:9, V3 = 10:12))

3 个答案:

答案 0 :(得分:1)

您的问题标题明确指出您希望在没有aes_string的情况下执行此操作。以下是aes_string的使用方法:使用paste

plot_vs <- function(df, count = 2) {
  vs <- paste0('V', seq_len(count)) # 'V1', 'V2', ...
  for (v in vs) {
    print(ggplot(df, aes_string(paste("seq_along(", v, ")"), v)) + geom_point())
  }
}

plot_vs(data.frame(V1 = 4:6, V2 =7:9, V3 = 10:12))

答案 1 :(得分:0)

library(ggplot2)
df <- data.frame(a = c(.4, .5, .2))
v <- "a"
df$num<-seq(nrow(df))
ggplot(df, aes_string("num", v)) + geom_point()

答案 2 :(得分:0)

@ shadow的评论给出了提示找到解决方案,即aes_q

plot_vs <- function(df, count = 2) {
    vs <- paste0('V', seq_len(count)) # 'V1', 'V2', ...
    for (v in vs) {
        v = as.name(v)
        print(ggplot(df, aes_q(substitute(seq_along(v)), v)) + geom_point())
    }
}
plot_vs(data.frame(V1 = 4:6, V2 = 7:9, V3 = 10:12))