UPDATE: Note that in more recent version of ggplot2
, the use of aes_string
is discouraged. Instead if you need to get a column value from a string, use the .data
pronoun
ggplot(data=mydat, aes(x=,.data[[xcol]], y=.data[[ycol]])) + geom_point()
ORIGINAL ANSWER: Values passed to aes_string
are parse()
-d. This is because you can pass things like aes_string(x="log(price)")
where you aren't passing a column name but an expression. So it treats your string like an expression and when it goes to parse it, it finds the space and that's an invalid expression. You can "fix" this by wrapping column names in quotes. For example, this works
mydat <- data.frame(`Col 1`=1:5, `Col 2`=1:5, check.names=F)
xcol <- "Col 1"
ycol <- "Col 2"
ggplot(data=mydat, aes_string(x=shQuote(xcol), y=shQuote(ycol))) + geom_point()
We just use shQuote()
to but double quotes around our values. You could have also embedded the single ticks like you did in the other example in your string
mydat <- data.frame(`Col 1`=1:5, `Col 2`=1:5, check.names=F)
xcol <- "`Col 1`"
ycol <- "`Col 2`"
ggplot(data=mydat, aes_string(x=xcol, y=ycol)) + geom_point()
But the real best way to deal with this is to not use column names that are not valid variable names.