Home > Enterprise >  Add additional legend item to ggplot2 for overlapping fill (geom_rect)
Add additional legend item to ggplot2 for overlapping fill (geom_rect)

Time:12-08

I would like to add an additional item to a ggplot2 legend for the overlapping part/color of two geom_rect.

Reprex:

# library
library(ggplot2)
library(tidyverse)

# make colors
adjustcolor("red", alpha.f = 0.1) -> red.tra
adjustcolor("blue", alpha.f = 0.1) -> blue.tra

#get data

data <-  structure(list(unclear = c(0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 
                                    1), start = structure(c(12784, 13879, 9496, 17897, 11323, 12053, 
                                                            16801, 16071, 17167, 17532, 16071, 11323, 11688), class = "Date"), 
                        stop = structure(c(18628, 18628, 16801, 18262, 13879, 17897, 
                                           18262, 17897, 17532, 18628, 17897, 18262, 11688), class = "Date"), 
                        group = c("R", "C", "C", "A", "A", "R", "M", "N", 
                                            "N", "O", "OB", "H", "H")), class = "data.frame", row.names = c(NA, 
                                                                                                            -13L))                                                                                                                                                         


#plot
ggplot(data = data) 
  geom_rect(data = data %>% filter(unclear==0), aes(xmin=start, xmax=stop, ymin=0, ymax=0.7, fill="one"))  
  geom_rect(data = data %>% filter(unclear==1), aes(xmin=start, xmax=stop, ymin=0, ymax=0.7, fill="two")) 
  scale_fill_manual("colors",values=c(red.tra,blue.tra), labels=c("one","two")) 
  facet_wrap(~group, ncol = 1, strip.position = "left") 

Created on 2022-12-08 with enter image description here

  • Related