1

This is an example of my plot. Notice how the boxplots are next to each other. I want to figure out if there is a way to stack the box plots on top of each other. example plots

bdecaf
  • 4,652
  • 23
  • 44
  • What exactly do you mean by stack them on top of each other? Do you have an example image showing what you want? It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Apr 16 '21 at 04:18
  • 3
    If you put `position = "identity"` inside `geom_boxplot`, they won't be "dodged". This will put them on top of each other and likely make them illegible. – Gregor Thomas Apr 16 '21 at 05:00

1 Answers1

5

Update Because it was a challenging task I got a little further: The main hint was in the comments of Gregor Thomas. I searched a little and found this geom_boxplot: map alpha levels to whiskers & outliers

The result: Plot A can be shown as plot B with the code below: enter image description here

library(ggplot2)
library(cowplot)

df <- diamonds

# defining individual alpha levels
# learned here https://stackoverflow.com/questions/34618517/geom-boxplot-map-alpha-levels-to-whiskers-outliers
numVals = length(unique(iris$Species))
avals = seq(0.1, 0.4, length.out=numVals)

avalsHex = paste0("#000000", toupper(as.hexmode(round(avals*255))))

# the plots with some data tweaking
p1 <- df %>% 
  mutate(color = fct_lump(color, 2),
         mutate = fct_reorder(color, depth)) %>% 
  ggplot(aes(cut, depth))+
  geom_boxplot(aes(fill=color, alpha=color)) +
  scale_alpha_manual(values = avals) +
  scale_colour_manual(values = avalsHex) +
  theme_void()

p2 <- df %>% 
  mutate(color = fct_lump(color, 2),
         mutate = fct_reorder(color, depth)) %>% 
  ggplot(aes(cut, depth))+
  geom_boxplot(aes(fill=color, alpha=color), position = "identity") +
  scale_alpha_manual(values = avals) +
  scale_colour_manual(values = avalsHex) +
  theme_void()

plot_grid(p1, p2, labels = "AUTO")

First answer: I am not sure, but you can achieve a kind of stacking with coord_flip. See my example with diamonds dataset. This means to just show the boxplots without the dots.

ggplot(diamonds, aes(x = cut, y = depth, fill = color)) +
  geom_boxplot() +
  coord_flip()

enter image description here

TarJae
  • 72,363
  • 6
  • 19
  • 66