2017-10-21 70 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)