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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…