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?