Tidy evaluation programming and ggplot2

后端 未结 2 1057
無奈伤痛
無奈伤痛 2021-01-02 00:57

Trying to write a relatively simple wrapper to produce some plots, but can not work out how to specify tidy evaluation of grouping variables specified as ... an

2条回答
  •  天命终不由人
    2021-01-02 01:32

    I'm not sure I understand the question. Does this satisfy the requirements?

    library(ggplot2)
    library(data.table)
    
    your_plot <- function(df, select, color=NULL) {
    
      df <- as.data.table(df)[, mget(na.omit(c(select, color)))]
    
      ggplot(melt(df, color, select), aes_string(x=quote(value), color=color)) +
        geom_histogram(stat="count") +
        facet_wrap(~variable, scales="free", strip.position="bottom")
    
    }
    
    your_plot(dplyr::starwars, c("height", "mass"), "hair_color")
    

    This uses melt to stack the select variables, with the color variable(s) repeated for each stack. It also uses aes_string, since aes(x=value, color=color) fails when color=NULL.

提交回复
热议问题