0

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:

enter image description here

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!

  • 1
    Do you mean the boxplots you get when you use `aes(x = xval, y = yval, group = as.character(xval))`? – teunbrand Aug 06 '21 at 20:07
  • 1
    It sounds like you want boxplots on a continuous x axis. If so, the duplicate question above isn't quite right. This one should get you on the right path: https://stackoverflow.com/questions/53245233/how-to-plot-a-boxplot-with-correctly-spaced-continuous-x-axis-values-in-ggplot2 – blongworth Aug 07 '21 at 12:14
  • yes, that's correct! the duplicated question above isn't what I want but this one is. Thank you very much! – Peter Thompson Aug 07 '21 at 16:04

0 Answers0