How to use a variable to specify column name in ggplot

前端 未结 6 1523
别那么骄傲
别那么骄傲 2020-11-22 03:41

I have a ggplot command

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

inside a function. But I would like to be a

6条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 04:21

    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) ) )
    

提交回复
热议问题