How to use a variable to specify column name in ggplot

前端 未结 6 1470
别那么骄傲
别那么骄傲 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条回答
  •  天涯浪人
    2020-11-22 04:29

    Another option (ggplot2 > 3.0.0) is to use the tidy evaluation pronoun .data to slice the chosen variable/column from the rates.by.groups data frame.

    library(ggplot2)
    theme_set(theme_classic(base_size = 14))
    
    # created by @Moody_Mudskipper
    rates.by.groups <- data.frame(
      name = LETTERS[1:3],
      rate = 1:3,
      mjr = LETTERS[c(4, 4, 5)],
      gender = c("M", "F", "F")
    )
    
    f1 <- function(df, column) {
      gg <- ggplot(df, 
             aes(x = name, 
                 y = rate, 
                 fill  = .data[[column]], 
                 group = .data[[column]])) +
        geom_col() +
        labs(fill = column)
      return(gg)
    }
    
    plot_list <- lapply(list("gender", "mjr"), function(x){ f1(rates.by.groups, x) })
    plot_list
    #> [[1]]
    

    #> 
    #> [[2]]
    

    # combine all plots
    library(egg)
    ggarrange(plots = plot_list,
              nrow = 2,
              labels = c('A)', 'B)'))
    

    Created on 2019-04-04 by the reprex package (v0.2.1.9000)

提交回复
热议问题