Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

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

I'm making plots of one y variable against multiple x variables. I have a working solution using lapply. However, I can't manage to write the name of the x variable as the x label for each plot. Here's a simplified example of what I have:

The goal is to plot the y variable against each x variable resulting in three plots and adding the name of each x variable as the x axis label.

Generate a dataframe with one y variable and three x variables:

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

A function that is supposed to retrieve the variable name as a string:

get_name <- function(v1) {deparse(substitute(v1))}

The function that generates the plot of y against an x variable:

generate_plot <- function(x.variable) {ggplot(data = df, aes(x.variable, y.variable )) +geom_point()  + xlab(get_name(variable.name))}

A call to lapply to perform generate_plot on each column of df:

lapply(df, generate_plot)

This results in three plots, each of which has "variable.x" as its x-label instead of the desired variable name x1, x2 and x3.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

enter image description here

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...