2

I have a histogram that is plotting 2 different groups with some overlap between them. I have been able to manually color the groups and a legend is generated for each group, however I am asking how to add into the legend a color and label for the overlapping part?

Histogram Overlapping Example

For example, in the above histogram I would like to add a legend for the purplish part where A and B overlap (which should be labeled as "Overlap" in the legend, underneath B).

Code for generating above histogram:

set.seed(42)  
n <- 100
dat <- data.frame(id=1:n, 
                  group=rep(LETTERS[1:2], n/2),
                  x=rnorm(n))


ggplot(dat, aes(x=x, fill=group)) + geom_histogram(alpha=.5, position="identity") +
  scale_fill_manual(values=c("blue","red"))
Cyph
  • 71
  • 5
  • 3
    Kind of the same as this: https://stackoverflow.com/questions/4981764/r-ggplot2-how-to-match-legend-and-plot-colors-in-overlapping-area-plots Basically ggplot doesn't really have anything built in to the with that. Probably better if you actually manipulate your data before plotting into three groups then use a barplot rather than a histogram. – MrFlick Mar 07 '22 at 05:17

1 Answers1

0

A partially overlap solution

Sample code:

  library(ggplot2)

  ggplot(dat, aes(x=x, fill=group)) + 
      geom_histogram(position = position_dodge(width = 0.6))+
      scale_fill_manual(values=c("blue","red"))+
      scale_y_continuous(expand=c(0,0))+
      theme_bw()

Plot:

enter image description here

Rfanatic
  • 2,224
  • 1
  • 5
  • 21