参考文章;
https://stackoverflow.com/questions/22309285/how-to-use-a-variable-to-specify-column-name-in-ggplot
用get 或者 !! 方法 方法:
ggplot( rates.by.groups, aes(x=name, y=rate, colour= get(column), group=get(column) ) )
ggplot( rates.by.groups, aes(x=name, y=rate, colour= !!(column), group=!!(column) ) )
用aes_string 方法
f <- function( column ) { ... ggplot( rates.by.groups, aes_string(x="name", y="rate", colour= column, group=column ) ) }
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]]
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!