rggplot2facet

Free scales for facets in facet_grid change pattern


I have a data set containing mass for different treatments at two experimental areas. There's 2 treatments at one area and 4 at another. I now would like to plot this data, using facet_grid() to facet the data from the two areas. Additionally, I have in general much higher values at one area (i.e. in one facet) than the other.

I would like a plot where 1) the discrete x-axis scale is free, so the boxplots have the same size in both facets while the facet-boxes vary in width and 2) the continues y-axis is also free, as the values differ so much. Using the ggh4x package I can do what I want, but setting the discrete x-axis free messes with the pattern of the boxplots: It somehow makes the distances between the stripes smaller for the narrower facet box, even though I specify it manually?

enter image description here

Is there a way to keep the pattern constant?

My code at the moment:

# generate data
treat1 <- c(rep("bare",10), rep("veg",10), rep("bare",10), rep("veg",10), rep("bare",10), rep("veg",10))
treat2 <- c(rep("wet",10), rep("wet",10), rep("wet",10), rep("wet",10), rep("dry",10), rep("dry",10))
area <- c(rep("down",10), rep("down",10), rep("up",10), rep("up",10), rep("up",10), rep("up",10))
weight <- c(runif(10, 20, 50), runif(10, 1, 15), runif(10, 1, 10), runif(10, 1, 5), runif(10, 1, 10), runif(10, 1, 5))

dat_exp <- tibble("treat1" = treat1, "treat2" = treat2, "area" = area, "mass" = weight) %>%
  mutate(treat2_area = paste(treat2, area, sep = "."),
         treat1_treat2 = paste(treat1, treat2, sep = "."))


# plot it

ggplot(data = dat_exp, aes(x= treat1_treat2, y = mass, fill = treat2_area, pattern = treat1)) +
  theme_bw() +
  geom_boxplot_pattern(position = position_dodge(preserve = "single"), color = "black", pattern_colour = "white", pattern_fill = "white", pattern_angle = 45, pattern_density = 0.3, pattern_spacing = 0.025, pattern_key_scale_factor = 0.6) +
  scale_pattern_manual(values = c(bare = "stripe", veg = "none")) +
  ggh4x::facet_grid2(. ~ area, space = "free_x", scales = "free", independent = "y", switch = "both")

Solution

  • That's because you need to specify pattern spacing in some absolute units (like mm or cm) using unit() function from ggplot2 package:

    ggplot(data = dat_exp, aes(x= treat1_treat2, y = mass, fill = treat2_area, pattern = treat1)) +
      theme_bw() +
      geom_boxplot_pattern(position = position_dodge(preserve = "single"), color = "black", pattern_colour = "white", pattern_fill = "white", pattern_angle = 45, pattern_density = 0.3, pattern_spacing = unit(1, "mm"), pattern_key_scale_factor = 0.6) +
      scale_pattern_manual(values = c(bare = "stripe", veg = "none")) +
      ggh4x::facet_grid2(. ~ area, space = "free_x", scales = "free", independent = "y", switch = "both")
    

    enter image description here