Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a facet_wrap (ggplot2) within a function

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?

like image 634
ant Avatar asked Nov 17 '16 01:11

ant


People also ask

What does Facet_wrap do in Ggplot?

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.

What is the difference between Facet_wrap and Facet_grid?

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.


1 Answers

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

like image 114
eipi10 Avatar answered Sep 19 '22 16:09

eipi10