I have this function that generates a box plot:
generate_box <- function (df, x, y) {
sort_order <- c("Strongly negative", "Negative", "Neutral", "Positive", "Strongly positive")
gg <- df %>%
mutate(x = factor(x, levels = sort_order)) %>%
ggplot(aes_string(x = x, y = y, fill = x)) +
geom_boxplot(outlier.size = 3, outlier.color = '#121212')
return (gg)
}
I'm calling the function like this:
plot <- generate_box(df, 'x_variable', 'y_variable')
The plot is generated successfully; however, the factors are NOT reordered. I think the problem is the way I'm referencing the x variable. Because the same implementation worked outside the function in the global environment.
What should this line be for the function to work properly?
mutate(x = factor(x, levels = sort_order))