0

I am working on a graph and am using color and pattern for two different variables. I want the graph to have colored designs created by using a white pattern over the colored fills. (I tried making the pattern colored, but when the pattern color and pattern designs are different variables, I couldn't make that work.) However, the pattern designs in the legend for the pattern are nearly invisible. Is there a way to manually add a grey fill to the boxes in that part of the legend? I would also like to remove the pattern from the color part of the legend as well if that is possible.

I've included my code adapted to the mtcars dataset to show an example.

library(ggplot2)
library(ggpattern)

dataset <- mtcars

dataset$cyl <- as.factor(dataset$cyl)
dataset$gear <- as.factor(dataset$gear)

ggplot(data=dataset,
       aes(x=gear, y=mpg, pattern=cyl, fill=gear, facet.by=cyl)) +
  stat_boxplot(inherit.aes=T, geom ='errorbar', width = 0.6, lwd=1, 
               position=position_dodge(0.8), color="black")+
  geom_boxplot_pattern(width=0.8, lwd=1, color="black",alpha=0.6, 
                       outlier.size=1,
                       pattern_fill = "white",
                       pattern_angle = 45,
                       pattern_density = 0.4,
                       pattern_spacing = 0.03,
                       pattern_key_scale_factor = 1,
                       pattern_alpha = 1,
                       pattern_linetype=0,
                       show.legend = T) + 
  scale_pattern_manual(values=c(`4`="none", `6`="stripe", `8`="crosshatch")) +
  scale_fill_manual(values=c(`3`="red", `4`="blue", `5`="green"))+
  scale_y_continuous(limits = c(0, NA), expand=expansion(mult=c(0,0.2)))

1 Answer 1

0

To change these details about a guide in ggplot, we can pass a guide to the scale function. In this case, we want to override some particular aesthetics in the guide:

For pattern, we want to override the fill to always be grey:

pattern_guide <- guide_legend(override.aes = list(pattern_fill = 'grey'))

And for fill, we always want the "none" pattern:

fill_guide <- guide_legend(override.aes = list(pattern = 'none'))

Use like so:

your_ggplot_code +
  scale_pattern_manual(
    values = c(`4`="none", `6`="stripe", `8`="crosshatch"),
    guide = pattern_guide
  ) +
  scale_fill_manual(
    values=c(`3`="red", `4`="blue", `5`="green"),
    guide = fill_guide
  )
1
  • Thanks! This really helps. Is there a way to override the background with grey instead of the pattern_fill? Commented Aug 24, 2023 at 19:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.