[R] ggplot's aes_ doesn't work as expected for x=factor()

Waichler, Scott R Scott.Waichler at pnnl.gov
Mon Aug 14 01:38:07 CEST 2017


I'm learning how to use ggplot in a programming approach where I supply variable names on the fly.  Using aes_ doesn't work as I expected when x = factor(x).  Is this a bug or am I not understanding something?

# toy dataset
df <- data.frame(LogicalVar = c(FALSE, TRUE, FALSE, TRUE, FALSE, TRUE),
                 Var1 = c(0.01, 0.01, 1, 1, 30, 30),
                 pct1 = c(12, 88, 60, 40, 93, 7),
                 Var2 = c(2, 2, 4, 4, 8, 8),
                 pct2 = c(43, 57, 10, 90, 50, 50)
                )
varnames <- names(df)
# using aes()--this works
ggplot(df, aes(x=factor(Var1), y=pct1, fill=LogicalVar)) + geom_bar(stat="identity")  # works

# using aes_() works in this instance
ggplot(df, aes_(x=as.name(varnames[2]), y=as.name(varnames[3]), fill=as.name(varnames[1]))) + geom_bar(stat="identity")  # works

# it doesn't work here, where only change is using x=factor()
ggplot(df, aes_(x=factor(as.name(varnames[2])), y=as.name(varnames[3]), fill=as.name(varnames[1]))) + geom_bar(stat="identity") # doesn't work
Error in unique.default(x, nmax = nmax) :
  unique() applies only to vectors

# aes_ does work if I make the x variable a factor ahead of time
df2 <- df
df2$Var1 <- as.factor(df2$Var1)
ggplot(df2, aes_(x=as.name(varnames[2]), y=as.name(varnames[3]), fill=as.name(varnames[1]))) + geom_bar(stat="identity") # works

Regards,
Scott Waichler
Pacific Northwest National Laboratory
Richland, WA, USA



More information about the R-help mailing list