flying sheep
flying sheep

Reputation: 8972

ggplot: aesthetics from variable string without aes_string

i have a variable v containing a data.frame column name.

I now want to plot it against its index.

Normally, plotting a column against its index is easy:

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

But in my case, I can’t figure out what incantations to do:

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))

Upvotes: 0

Views: 1048

Answers (3)

flying sheep
flying sheep

Reputation: 8972

@shadow’s comment gave the hint to find the solution, namely 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))

Upvotes: 0

shadow
shadow

Reputation: 22353

Your question title explicitly states that you want to do this without aes_string. Here's how you do it with aes_string: use 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))

Upvotes: 1

Anthony Damico
Anthony Damico

Reputation: 6124

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()

Upvotes: 0

Related Questions