0

I would like to set distinct patterns for my box and whisker plot variables.

I have tried using scale_pattern_manual() but it is not setting distinct patterns for each variable and is setting a stripe pattern to all variables.

DF2 <- data.frame(
  x = c(c(A1, A2, A3), c(B1, B2, B3)),
  y = rep(c("A", "B"), each = 15),
  z = rep(rep(1:3, each=5), 2),
  stringsAsFactors = FALSE
)
cols <- rainbow(3, s = 0.5)
boxplot(x ~ z + y, data = DF2,
        at = c(1:3, 5:7), col = cols,
        names = c("", "A", "", "", "B", ""), xaxs = FALSE)
library(ggplot2)
ggplot(DF2, aes(y, x, fill=factor(z))) +
  geom_boxplot_pattern() + scale_pattern_manual(values = c("wave","stripe","crosshatch"))
wibeasley
  • 5,000
  • 3
  • 34
  • 62
Hazel
  • 1
  • Welcome to Stack Overflow! Thanks for accompanying your question with a reproducible example. Will you see if you can run it in a *new* R session. I think it has a few problems such as (a) on line 2, the values like `A1` should be `"A1"` and (b) you're missing at least one `library()` call to ggpattern. – wibeasley Mar 09 '23 at 19:17
  • To have different patterns you have to map on the `pattern` aes, i.e. try `aes(..., pattern = factor(z))` – stefan Mar 09 '23 at 19:21

1 Answers1

0

I think you were close, but the variables were mapped to the wrong aesthetics. Please check my assumptions/modifications.

  • I don't think x needs to be passed to ggplot at all.
  • z is the only quantitative variable, so it seems like your outcome variable (so I mapped it to the y aesthetic).
  • y has the values of "A" and "B", which should have different patterns
  • The y factor has only two levels, so the crosshatch pattern is never used.
DF2 <- data.frame(
  x = c(c("A1", "A2", "A3"), c("B1", "B2", "B3")),
  y = rep(c("A", "B"), each = 15),
  z = rep(rep(1:3, each=5), 2)
)

library(ggplot2)
library(ggpattern)
ggplot(DF2, aes(x = 1, y = z, fill = factor(y), pattern = factor(y))) +
  geom_boxplot_pattern() + ggplot(DF2, aes(x = 1, y = z, fill = factor(y), pattern = factor(y))) +
  geom_boxplot_pattern() + 
  scale_pattern_manual(values = c("A" = "none", "B" = "stripe", "C" = "crosshatch"))

enter image description here

wibeasley
  • 5,000
  • 3
  • 34
  • 62
  • Thank you it worked! Is there a way to make one variable a solid color and another just stripes? – Hazel Mar 09 '23 at 20:32
  • Glad that meets your needs --see the edit. Set the pattern to "none". Don't forget to mark it as answered and then upvote any answers that you find helped. – wibeasley Mar 09 '23 at 20:46