0

How do you wade through the eval(), parse() and other-function swamp? This should be straightforward, thus I omit the data.

Original code, with attributes in the data set and a workaround for the chart title.

require(ggplot2)
ggplot(data = qs) + geom_bar(aes(x = G74_Q0005b)) + 
      ggtitle(attr(qs, "variable.labels")[grep("G74_Q0005b", names(qs))])

Here is a function that simply passes the variable name:

plot.label <- function(var){
  ggplot(data = qs) + geom_bar(aes(x = var)) + 
    ggtitle(attr(qs, "variable.labels")[grep(var, names(qs))])
  }

But obviously var alone is not enough and I am no programmer.

Possibly related?

Community
  • 1
  • 1
Rico
  • 1,998
  • 3
  • 24
  • 46

1 Answers1

1

You need to use aes_string for the aesthetics part. This takes a variable containing a string as an argument.

plot.label <- function(var){
  ggplot(data = qs) + geom_bar(aes_string(x = var)) + 
    ggtitle(attr(qs, "variable.labels")[grep(var, names(qs))])
  }
Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
  • Yes, that works...is this ggplot idiosyncrasy? – Rico Jan 03 '14 at 16:14
  • 2
    @Rico Not sure I'd call it an idiosyncrasy. The "normal" way to specify variables inside of `aes()` (unquoted variable names) is arguably more unusual, as it uses non-standard evaluation. The `aes_string` function is provided specifically for this purpose. – joran Jan 03 '14 at 16:19