Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use dplyr SE with ggplot2

Tags:

r

dplyr

ggplot2

I often combine dplyr with ggplot2 in wrapper functions for analysis. As I am moving to the new NSE / SE paradigm of v.0.7.1 with tidyeval, I am struggling to get this combination to work. I found that ggplot does not understand unquoted quosers (yet). 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 currently use the following work-around. But I assume there must 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 the best way to combine these two. Thanks!

like image 698
Edwin Avatar asked Dec 09 '25 13:12

Edwin


1 Answers

If you are already handling quosures it's easier to use aes_ which accepts inputs quoted 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)
like image 94
Stanwood Avatar answered Dec 11 '25 02:12

Stanwood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!