Skip to content
Prev 383721 / 398502 Next

Adding overlap legend to a histogram

Hi Ogbos,
While this solution is not entirely correct, I think it is a start.
First I took your data files and made them "sourceable" by adding
"FD[1|2]<-" at the top and renaming them "FD1.R" and "FD2.R". Running
the following code produces something that is at least close to what
you want. The code is fairly well commented so it should be easy to
see what I have done:

# read in the FD1 data
source("FD1.R")
# read in the FD2 data
source("FD2.R")
# convert year-month-day columns to dates
FD1$data.year<-FD1$data.year+ifelse(FD1$data.year < 50,2000,1900)
FD1$date<-as.Date(paste(FD1$data.year,FD1$data.month,FD1$data.day,sep="-"),
 format="%Y-%m-%d")
FD2$data.year<-FD2$data.year+ifelse(FD2$data.year < 50,2000,1900)
FD2$date<-as.Date(paste(FD2$data.year,FD2$data.month,FD2$data.day,sep="-"),
 format="%Y-%m-%d")
# check the ranges for overlap
range(FD1$date)
range(FD2$date)
# get the overall range of the plot
xlim<-range(c(FD1$date,FD2$date))
# FD1 spans the date range so xlim is not really needed here
# now get the counts for each data set
FD1counts<-as.vector(table(cut(FD1$date,breaks="years")))
# FD2 is missing 1996, 1997 and 2016 so add zeros at the beginning and end
FD2counts<-c(0,0,as.vector(table(cut(FD2$date,breaks="years"))),0)
# set up the bar colors
barcol<-matrix(c(rep("red",2),rep("blue",18),"red",
 rep("red",2),rep("green",18),"red"),nrow=2,byrow=TRUE)
# use barp as barplot can't do the colors
library(plotrix)
barp(rbind(FD1counts,FD2counts),names.arg=1996:2016,
 main="Observation counts for FD1 and FD2",
 xlab="Year",ylab="Observations",col=barcol)
legend(12,80,c("FD1 only","FD1 & FD2","FD2 & FD1"),
 fill=c("red","blue","green"))

This shows the overlap in blue and green. You can make the overlap
colors whatever you like. It doesn't account for the fact that FD2
only overlaps for part of a year on both ends. You may not be worried
about this.

Jim
On Fri, May 8, 2020 at 4:07 PM Ogbos Okike <giftedlife2014 at gmail.com> wrote: