How to use a variable to specify column name in ggplot

Note: the solution in this answer is “soft-deprecated”. See the answer below using .data[[ for the currently preferred method.

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

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)