Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the pattern background in legend keys?

I need to use colours and patterns independently to properly display my data, for this I use geom_col_pattern(). The issue I have is that in the legend the background is so dark, that the pattern is not clearly visible. It is not an issue of legend key size, as the pattern does show.

enter image description here

Here is the code I used:

library(dplyr)
library(ggplot2)
library(ggpattern)

mycars<-mtcars %>% head(10)
mycars$gear<-as.character(mycars$gear)
mycars$am<-as.character(mycars$am)

ggplot(mycars, aes(x=rownames(mycars),y=mpg, pattern=vs, group=gear, fill=gear))+
  geom_col_pattern(
    aes(
      pattern_density=am),
position=position_dodge2 (), 
pattern="stripe",
pattern_fill='grey40',
pattern_colour="grey40")+
  theme(strip.text = element_text(size = 4),legend.position="right", 
    axis.ticks.x = element_blank(),  axis.line.x = element_blank(),
    axis.text.x = element_blank(), axis.title.x=element_blank(),
  )
like image 760
Becci Avatar asked Jan 18 '26 03:01

Becci


1 Answers

We could override the aesthetics of the legend keys to change the patterns spacing and fill color. I have also added colour = "black" to have a box around the keys.

ggplot(mycars, 
       aes(x=rownames(mycars), y=mpg, 
           pattern=vs, group=gear, fill=gear)) +
  geom_col_pattern(aes(pattern_density=am),
    position=position_dodge2(), 
    pattern="stripe", pattern_fill='grey40', pattern_colour="grey40") +
  theme_bw() +
  theme(strip.text = element_text(size = 4), 
        legend.position="right", 
        axis.ticks.x = element_blank(),  
        axis.line.x = element_blank(),
        axis.text.x = element_blank(), 
        axis.title.x=element_blank()) + 
  guides(pattern_density = guide_legend(override.aes = list(
    pattern_spacing = 0.03, fill = "white", colour = "black"))))

Created on 2025-07-02 with reprex v2.1.1

like image 123
M-- Avatar answered Jan 20 '26 17:01

M--