How to set ggplot x-label equal to variable name during lapply?

耗尽温柔 提交于 2019-11-28 12:43:11

I modify your generate_plot a little bit and use the version of ggplot2 (> v3.0.0) which supports tidy evaluation

Explanation:

  • Inside the function, we use rlang::sym to turn a string into a symbol then unquote it inside aes using !! (bang bang)

  • To call the function, use purrr::map to loop through df column names

See more:

library(tidyverse)

df <- data.frame(y.variable=c(11:20), 
                 x1=c(21:30), x2=c(1:10), x3=c(31:40))

generate_plot2 <- function(df, x.variable) {
  x.variable <- rlang::sym(x.variable)

  ggplot(data = df, aes(!! x.variable, y.variable )) +
    geom_point() + 
    xlab(x.variable)
}

names(df)[-1] %>% 
  map(~ generate_plot2(df, .x))

Created on 2018-04-20 by the reprex package (v0.2.0).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!