【问题标题】:dplyr and ggplot in a function: use reorder in aes function函数中的 dplyr 和 ggplot:在 aes 函数中使用重新排序
【发布时间】:2016-06-26 06:48:43
【问题描述】:

我正在努力重新排序我的数据,以便在一个也使用 dplyr 的函数中使用 ggplot 进行绘图:

# example data
library(ggplot2)
library(dplyr)
dat <- data.frame(a = c(rep("l", 10), rep("m", 5), rep("o", 15)),
                  b = sample(100, 30), 
                  c= c(rep("q", 10), rep("r", 5), rep("s", 15)))

这是我在函数之外的步骤:

# set a variable
colm <- "a"
# make a table
dat1 <- dat %>% 
  group_by_(colm) %>%  
  tally(sort = TRUE)
# put in order and plot
ggplot(dat2, aes(x = reorder(a, n), y = n)) +
  geom_bar(stat = "identity")

但是当我尝试将它变成一个函数时,我似乎无法使用reorder

f <-  function(the_data, the_column){
       dat %>% group_by_(the_column) %>%  
       tally(sort = TRUE) %>% 
       ggplot(aes_string(x = reorder(the_column, 'n'), y = 'n')) +
       geom_bar(stat = "identity")
}

f(dat, "a")

Warning message:
In mean.default(X[[i]], ...) :
  argument is not numeric or logical: returning NA

没有reorder,该功能也可以工作:

f <-  function(the_data, the_column){
       dat %>% group_by_(the_column) %>%  
       tally(sort = TRUE) %>% 
       ggplot(aes_string(x = the_column, y = 'n')) +
       geom_bar(stat = "identity")
}

f(dat, "a")

而且我可以在没有 dplyr 的情况下得到我想要的,但我更喜欢使用 dplyr,因为它在我的实际用例中更有效:

# without dplyr
ff = function(the_data, the_column) {
  data.frame(table(the_data[the_column])) %>% 
  ggplot(aes(x = reorder(Var1, Freq), y = Freq)) +
  geom_bar(stat = "identity") +
    ylab("n") +
    xlab(the_column)
}

ff(dat, "a")

我看到其他人一直在努力解决这个问题(12),但似乎必须有一个更有效的 dplyr/pipe 习惯用法来完成这个函数中的重新排序任务。

【问题讨论】:

    标签: r ggplot2 dplyr


    【解决方案1】:

    如果你要使用aes_string,那么整个值必须是一个字符串,而不仅仅是部分字符串。您可以使用paste() 来帮助构建您想要用于x 的表达式。例如

    f <-  function(the_data, the_column){
           dat %>% group_by_(the_column) %>%  
           tally(sort = TRUE) %>% 
           ggplot(aes_string(x = paste0("reorder(",the_column,", n)"), y = 'n')) +
           geom_bar(stat = "identity")
    }
    

    或者你可以使用表达式而不是字符串

    f <-  function(the_data, the_column){
           dat %>% group_by_(the_column) %>%  
           tally(sort = TRUE) %>% 
           ggplot(aes_q(x = substitute(reorder(x, n),list(x=as.name(the_column))), y = quote(n))) +
           geom_bar(stat = "identity")
    }
    

    但总体思路是,在混合字符串和原始语言元素(如名称或表达式)时需要小心。

    【讨论】:

    • 酷,谢谢,我以前没见过aes_q。我希望输入更少的东西,但这比摆弄因子订单等要好得多。
    猜你喜欢
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-08
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多