r - 函数 : use reorder in aes function 中的 dplyr 和 ggplot

标签 r ggplot2 dplyr

我正在努力重新排序我的数据,以便在一个也使用 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")

enter image description here

但是当我试图把它变成一个函数时,我似乎不能使用 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

enter image description here

该功能将在没有 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")

enter image description here

我可以在没有 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")

enter image description here

我看到其他人为此苦苦挣扎( 12 ),但似乎必须有一个更有效的 dplyr/pipe 习语来完成这个功能重排任务。

最佳答案

如果您打算使用 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")
}

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

关于r - 函数 : use reorder in aes function 中的 dplyr 和 ggplot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35933199/

相关文章:

r - 字符串作为公式

r - 相当于 Pandas Series/DataFrame 的 gsub

r - 图例在 ggplot2 密度图中不显示线型

r - 无法有条件地在ggplot中使轴标签加粗

R ggplot2 : legend should be discrete and not continuous

R:重构数据框

r - 使用标准评估更改 dplyr::count 中的变量名称

r - 行之间的条件时间差。研发&dplyr/data.table

r - 带有ggplot2::stat_qq的Q-Q图,颜色,单个组

r - dplyr错误:组合group_by,mutate和ifelse时出现奇怪的问题。是 bug 吗?