r - How to use a variable to specify column name in ggplot -
i have ggplot command
ggplot( rates.by.groups, aes(x=name, y=rate, colour=majr, group=majr) ) inside function. able use parameter of function pick out column use colour , group. i.e. this
f <- function( column ) { ... ggplot( rates.by.groups, aes(x=name, y=rate, colour= ??? , group=??? ) ) } so column used in ggplot determined parameter. e.g. f("majr") effect of
ggplot( rates.by.groups, aes(x=name, y=rate, colour=majr, group=majr) ) but f("gender") effect of
ggplot( rates.by.groups, aes(x=name, y=rate, colour=gender, group=gender) ) some things tried:
ggplot( rates.by.groups, aes(x=name, y=rate, colour= columnname , group=columnname ) ) did not work. nor did
e <- environment() ggplot( rates.by.groups, aes(x=name, y=rate, colour= columnname , group=columnname ), environment=e )
you can use aes_string:
f <- function( column ) { ... ggplot( rates.by.groups, aes_string(x="name", y="rate", colour= column, group=column ) ) } as long pass column function string (f("majr") rather f(majr)). note changed other columns, "name" , "rate", strings.
if whatever reason you'd rather not use aes_string, change (the more cumbersome):
ggplot( rates.by.groups, aes(x=name, y=rate, colour= get(column), group=get(column) ) )
Comments
Post a Comment