Use dplyr SE with ggplot2

I often combine dplyr with ggplot2 in the wrapper functions for analysis. As I move on to the new NSE / SE v.0.7.1 paradigm with tidyeval , I'm struggling to get this combination to work. I found that ggplot does not understand quotes without quotes (for now). The following does not work:

 example_func <- function(col) { col <- enquo(col) mtcars %>% count(!!col) %>% ggplot(aes((!!col), n)) + geom_bar(stat = "identity") } example_func(cyl) # Error in !col : invalid argument type 

I am currently using the following work. But I guess there should be a better way.

 example_func2 <- function(col) { col <- enquo(col) mtcars %>% count(!!col) %>% ggplot(aes_string(rlang::quo_text(col), "n")) + geom_bar(stat = "identity") } 

Please show me what is the best way to combine these two. Thanks!

+2
r ggplot2 dplyr
source share
2 answers

There seem to be two ways to think about this.

Approach 1: Separation of problems.

I like that my story materials are very different from my controversial things. In addition, you can name your group, which considers the easiest way to solve your problem [although you lose the original column name]. Thus, one way of deciding what you are trying to do is through;

 library(tidyverse) concern1_data <- function(df, col) { group <- enquo(col) df %>% group_by(group = !!group) %>% summarise(n = n()) } concern2_plotting <- function(df){ ggplot(data=df) + geom_bar(aes(group, n), stat = "identity") } mtcars %>% concern1_data(am) %>% concern2_plotting() 

This ensures that you are trying to do more or less, and keep problems separate (which deserves mention).

Approach 2: Accept and Wait

The fact is that tidyeval is not yet implemented in ggplot2. - Colin Fye from the link

I think this is support that is not currently in ggplot2, but I cannot imagine that ggplot2 will not receive this functionality. This is just not there.

+1
source share

If you are already processing quosures, it is easier to use aes_ , which accepts the inputs specified as a formula: aes_(col, ~n) .

This bit of code solves your problem:

 library(tidyverse) example_func <- function(col) { col <- enquo(col) mtcars %>% count(!!col) %>% ggplot(aes_(col, ~n)) + geom_bar(stat = "identity") } example_func(cyl) 
+1
source share

All Articles