How to supply variable names as strings in fct_reorder within ggplot code?

江枫思渺然 提交于 2021-02-08 10:24:09

问题


I want to create the geom_col chart by supplying the variable names as strings. I know the aes_string does that in the ggplot code. However, I am not sure how to handle the variables supplied in the fct_reorder to order the bars. Here is my wip code.

I want to convert this:

mpg %>% 
  ggplot() + 
  geom_col(aes(x = cty, y = fct_reorder(drv, cty, .fun = mean, na.rm = T), fill = drv), width = 0.8) +
  theme_classic()

into a function,

chart_fun <- function(x, y) {
  mpg %>%
    ggplot() +
    geom_col(aes_string(x = x, y = fct_reorder(y, x, .fun = mean, na.rm = T), fill = y), width = 0.8) +
    theme_classic()
}

chart_fun(x = "cty", y = "drv")

but I am getting an error, "Error: 1 components of ... were not used. We detected these problematic arguments: * na.rm Did you misspecify an argument?"

Help me fix this code.


回答1:


If you want to pass variables as strings you could also make use of the .data pronoun which allows you to stick with aes():

library(ggplot2)
library(dplyr)
library(forcats)

chart_fun <- function(x, y) {
  mpg %>%
    ggplot() +
    geom_col(aes(x = .data[[x]], y = fct_reorder(.data[[y]], .data[[x]], .fun = mean, na.rm = T), fill = .data[[y]]), width = 0.8) +
    theme_classic()
}

chart_fun(x = "cty", y = "drv")



来源:https://stackoverflow.com/questions/65597281/how-to-supply-variable-names-as-strings-in-fct-reorder-within-ggplot-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!