0

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))
SevenSouls
  • 539
  • 3
  • 12
  • 1
    Would it be possible for you to create a reproducible example? – Juan C Nov 02 '22 at 19:50
  • 1
    See [here](https://stackoverflow.com/questions/72581622/pass-string-as-the-argument-in-function-to-be-used-in-other-function-in-r) and [here](https://stackoverflow.com/questions/59690702/pass-a-string-as-variable-name-in-dplyrmutate) – Rui Barradas Nov 02 '22 at 19:50
  • @RuiBarradas Thank you! The second link has the answer! I wish there was a simpler way of programming with tidyverse. – SevenSouls Nov 02 '22 at 19:55
  • @SevenSouls there's a simpler answer – Juan C Nov 02 '22 at 20:21

0 Answers0