0

I have a lot of data for which I need to create bar graphs that are arranged in descending order. If I do it outside of a function, the solutions shown in this post work, but not when used inside the function.

Here is a use case.

library(forcats)
library(tidyverse)

dat <- data.frame(
  x = rep(letters[1:5], times=c(3,11,8, 2, 7))
)

plot_freq <- function(data, group,  n=10){
  group <- enquo(group)
  data %>%
    count(!!group) %>%
    top_n(n) %>%
    mutate(group := fct_reorder(!!group, n)) %>%
    ggplot(., aes_(group, quo(n))) + 
    geom_bar(stat = "identity") +
    coord_flip()
}


plot_freq(dat, x, n=5)

What else can I do with plot_freq that can give me my desired result?

enter image description here

hpesoj626
  • 3,529
  • 1
  • 17
  • 25

2 Answers2

2
dat %>% count(x) %>% top_n(5) %>% mutate(x = fct_reorder(x, n)) %>% 
    ggplot(., aes(x, n)) + geom_bar(stat = 'identity') + coord_flip()

enter image description here

You can change the function plot_freq accordingly

Change group to quo(group), similar to y aesthetic:

plot_freq <- function(data, group,  n=10){
    group <- enquo(group)
    data %>%
        count(!!group) %>%
        top_n(n) %>%
        mutate(group := fct_reorder(!!group, n)) %>%
        ggplot(., aes_(x=quo(group), y=quo(n))) + 
        geom_bar(stat = "identity") +
        coord_flip()
}

plot_freq(dat, x, n=5)
Prradep
  • 5,506
  • 5
  • 43
  • 84
1

Two solutions.

plot_freq <- function(data, group,  n=10){
  group <- enquo(group)
  data %>%
    count(!!group) %>%
    top_n(n) %>%
    mutate(group := fct_reorder(!!group, n)) %>%
    ggplot(., aes_(y=quo(n))) + 
    geom_bar(aes(group),stat = "identity") +
    coord_flip()
}

enter image description here

plot_freq <- function(data, group,  n=10){
  group <- enquo(group)
  data %>%
    count(!!group) %>%
    top_n(n) %>%
    mutate(group := fct_reorder(!!group, n)) %>%
    ggplot(., aes_(quo(group),quo(n))) + 
    geom_bar(stat = "identity") +
    coord_flip()
}
Marco Sandri
  • 23,289
  • 7
  • 54
  • 58
  • So I was only missing a `quo()` on the `group` in `ggplot`. What was happening there that it enabled reordering? – hpesoj626 Oct 21 '17 at 11:24
  • @hpesoj626 In my R 3.4.2 `aes(group,n)` works inside the `plot_freq` function. I do not understand why it does not work for you. – Marco Sandri Oct 21 '17 at 12:15
  • hmm... I am still investigating it. But it is a problem for another day. Right now I can am happy that my headache is over. And that is only because of a `quo()`. The shift to `tidyeval` messed up with a lot of my custom functions. Thanks for the help. – hpesoj626 Oct 21 '17 at 12:32