I'm interested in making a plot in R (preferably with ggplot2, but a base-R solution will also work for me) that consists of a series of boxplots. I'm aware of how to do this using basic ggplot2, but I want the position (along the x-axis) of the boxplots to depend explicitly on the group name, which in this case is a number. To illustrate, picture the (completely fake and meaningless) data frame I have below:
require(ggplot2)
example_df = data.frame(xval = rep(c(5, 10, 20, 50, 100, 200), each = 5), yval = rnorm(30))
example_df %>% ggplot(aes(x = as.character(xval), y = yval)) + geom_boxplot()
Here, the value of "xval" represents a meaningful number (e.g., amount of water given to a plant or something) as well as a group. The graph I would like would put the boxplot for the xval = 5
group at the x=5 line, and so on. What ggplot does automatically (as far as I know, I need to convert xval to a character for the code to even evaluate at all) is sort the x values alphabetically, producing a plot like the one below:
Is there a way to manually change the position of each individual box plot such that they all end up in the correct spot? Note that changing the xval values to "005", "010", etc would order them properly but the placements would still be inaccurate (e.g., the plots for xval = 100
and xval = 200
should be farther away from each other relative to xval = 5
and xval = 10
). Hopefully this makes sense and hopefully there is a solution!