0

I am currenty trying to order a bar plot in R. The plot gets created in a function using a passed variable for selecting the column. This is the basic function:

plotting <- function(column_to_use) {
  ggplot(iris, aes(x = Sepal.Length, ))+
    aes_string(y = column_to_use)+
    geom_col()
}

plotting("Species")

This produces the correct plot, but I still have to order it. I've tried both base-R reorder and forcats fct_reorder(). Code difference in bold.


# reorder
plotting <- function(column_to_use) {
  ggplot(iris, aes(x = Sepal.Length, ))+
    aes_string(y = reorder(iris[column_to_use],Sepal.Width))+
    geom_col()
}

plotting("Species")

 > Error in tapply(X = X, INDEX = x, FUN = FUN, ...) : 
 object 'Sepal.Width' not found 

I am using aes_string to convert the variable column name using non-standard evaluation and figure, that this doesn't work in reorder. Sadly, there is no reorder_ counterpart available.


# fct_reorder
plotting <- function(column_to_use) {
  iris %>%
    fct_reorder(iris[column_to_use],Sepal.Width) %>%
    ggplot( aes(x = Sepal.Length))+
    aes_string(y = column_to_use)+
    geom_col()
}

plotting("Species")
> Error: `f` must be a factor (or character vector).

What are better options to get the bars ordered by Sepal.Width?

sonder
  • 25
  • 3

2 Answers2

0

aes_string has been soft-deprecated. Try to use .data :

library(ggplot2)

plotting <- function(column_to_use) {
  ggplot(iris, aes(x = Sepal.Length, 
                   y = reorder(.data[[column_to_use]], Sepal.Width)))+
    geom_col()
}

plotting("Species")
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

We can convert to symbol and evaluate with !!. It can take both quoted as well as unquoted input

library(ggplot2)
plotting <- function(column_to_use) {
  ggplot(iris, aes(x = Sepal.Length, 
               y = reorder(!! ensym(column_to_use), Sepal.Width)))+
   geom_col()
}

plotting("Species")
plotting(Species)
akrun
  • 874,273
  • 37
  • 540
  • 662