I am working on a shiny app where the user selects which variables might be plotted using ggplot2, however I am completely unsure about the best way to convert character strings (which are the names of the variable to be plotted) in to suitable function arguments.
Consider the following very artificial, working example:
df <- data.frame(gp = factor(rep(letters[1:3], each = 10)),
y = rnorm(30))
ggplot(df, aes(x = gp, y = y)) +
geom_point() + facet_wrap(~gp)
Now, how would I tell ggplot to plot the 'gp' variable on the x axis, if all I have is a character string of the name of the variable?
I have whipped up the following, but is there a simpler and more conventional method? Note the different approaches I use in the aes() and facet_wrap() functions.
x.var <- "gp"
ggplot(df, aes(x=lol <- switch(x.var,"gp"=gp), y = y)) +
geom_point() + facet_wrap(as.formula(paste("~",x.var)))
Any insight is greatly appreciated!