ggplot中用字符窜传递变量名称列名等

ggplot中用字符窜传递变量名称列名等

参考文章;


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


  • 发表于 2021-05-21 13:47
  • 阅读 ( 1708 )
  • 分类:R

0 条评论

请先 登录 后评论
omicsgene
omicsgene

生物信息

658 篇文章

作家榜 »

  1. omicsgene 658 文章
  2. 安生水 328 文章
  3. Daitoue 167 文章
  4. 生物女学霸 120 文章
  5. 红橙子 78 文章
  6. CORNERSTONE 72 文章
  7. xun 67 文章
  8. rzx 67 文章