As far as I can tell, this should be done in three parts. There are a few limitations that I have found that I would appreciate someone fixing if I am wrong.
data <- data.frame(THEME_NAME = c(rep("A", 10), rep("B", 20), rep("C", 15))) my_var <- names(data)[1] df <- data %>% group_by_(my_var) %>% summarise(n = n()) %>% mutate(freq = n / sum(n)) %>% arrange(desc(freq)) df[[1]] <- factor(df[[1]], levels = unique(df[[1]])) ggplot(df, aes_string(x = my_var, y = "freq")) + geom_bar(stat="identity") + scale_y_continuous(labels=percent)
Trying to get all this, I ran into these problems:
- It is not possible to prevent
ggplot from arranging the x axis automatically without resetting your variable levels before calling. The only way to call ggplot is with reorder , which, as far as I know, cannot be used with aes_string . - Another idea I had was to use
mutate to reset levels. You need to use the s_mutate function from dplyrExras to use strings, but resetting levels from a dataset with channels does not work for strings.
The statement will look with mutate like this (what BTW works):
mutate(THEME_NAME = factor(THEME_NAME, levels=unique(THEME_NAME)))
but when using a version-accepting string, the levels remain unchanged:
s_mutate(my_var = factor(my_var, levels = unique(my_var)))
source share