I have written a function to plot a bar graph. But when I get to facet wrap the '~' sign is making things difficult.
rf.funct <- function(dat, predictor, feature){
ggplot(get(dat), aes(get(predictor), N)) +
geom_bar(stat = 'identity') +
facet_wrap(get(~feature)) # this is where the problem is
}
I've tried the following:
facet_wrap((get(~feature))) # invalid first argument
facet_wrap(paste0("~ ", get(feature))) # object 'feature' not found
How do i make sure the '~' sign gets included with the function?
facet_wrap() makes a long ribbon of panels (generated by any number of variables) and wraps it into 2d. This is useful if you have a single variable with many levels and want to arrange the plots in a more space efficient manner.
The facet_grid() function will produce a grid of plots for each combination of variables that you specify, even if some plots are empty. The facet_wrap() function will only produce plots for the combinations of variables that have values, which means it won't produce any empty plots.
You don't need to use get
. You've passed the data frame into the function using the dat
argument, so just feed dat
to ggplot and it will have the data from within its environment.
rf.funct <- function(dat, predictor, feature) {
ggplot(dat, aes_string(predictor, "N")) +
geom_bar(stat = 'identity') +
facet_wrap(feature)
}
The predictor
and feature
arguments should be entered as strings. Then you can use aes_string
to specify the aesthetics. facet_wrap
can now take a character vector directly, without need of a formula (as pointed out by @WeihuangWong).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With