2017-10-21 74 views
0

我有很多數據,需要按照降序排列創建條形圖。如果我在功能之外執行此操作,則此post中顯示的解決方案可以工作,但在功能內部使用時不適用。使用ggplot2,dplyr和forcats使用自定義函數繪製降頻條形圖

這是一個用例。

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) 

我還能做些什麼plot_freq可以給我想要的結果嗎?

enter image description here

回答

1

兩種解決方案。

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() 
} 
+0

所以我只是缺少一個'現狀()'在'ggplot'的'group'。那裏發生了什麼,它使重新排序? – hpesoj626

+0

@ hpesoj626在我的R 3.4.2'aes(group,n)'在'plot_freq'函數內工作。我不明白爲什麼它不適合你。 –

+0

嗯...我仍在調查它。但這是另一天的問題。現在我很高興我的頭痛已經結束。這只是因爲「quo()」。轉向'tidyeval'讓我的許多自定義功能搞砸了。謝謝您的幫助。 – hpesoj626

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

您可以將功能plot_freq相應

變化group改變quo(group),類似y美學:

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)