How to give different pattern for side by side boxplots in R

155 Views Asked by At

My code is:

ggplot(my_data, aes(x = factor(inst), y = value, fill = color)) + 
 geom_boxplot(position = position_dodge(width = 0.75)) +
 scale_fill_manual(values = c("blue" = "blue", "green" = "green", "red" = "red", "yellow" = 
 "yellow")) +
 theme_bw()

And it shows a graph like this:enter image description here

My grouping variable is color. How can I visualize the boxplots with different patterns inside,just black and white background, instead of colors.

1

There are 1 best solutions below

0
On BEST ANSWER

Here's an example which should help you see how it is done:

library(tidyverse)
library(ggpattern)

dat <- expand_grid(a = 1:5, b = c("blue", "green", "red", "yellow"))

my_data <-
  pmap_dfr(dat, function(a, b) {
  tibble(value = sample(randu$x, size = 20, replace = TRUE)) |> 
    mutate(inst = a, color = b)
}  ) 

ggplot(my_data, aes(x = factor(inst), y = value)) + 
  geom_boxplot_pattern(
    aes(pattern = color, pattern_angle = color, pattern_spacing = color),
    position = position_dodge(width = 0.75)
    ) +
  theme_bw()

Here's the output

{ggpattern} has really good documentation, and an example of what you want can be found here: https://coolbutuseless.github.io/package/ggpattern/articles/geom-gallery-geometry.html#bw-example