How to use a variable to specify column name in ggplot

You can use aes_string:

f <- function( column ) {
    ...
    ggplot( rates.by.groups, aes_string(x="name", y="rate", colour= column,
                                        group=column ) )
}

as long as you pass the column to the function as a string (f("majr") rather than f(majr)). Also note that we changed the other columns, "name" and "rate", to be strings.

If for whatever reason you’d rather not use aes_string, you could change it to (the somewhat more cumbersome):

    ggplot( rates.by.groups, aes(x=name, y=rate, colour= get(column),
                                        group=get(column) ) )

Leave a Comment