# function to overlay histograms

Here I have written a function putting together the info I found on this site to help you create two (or more if change appropriately) histograms in R.

`overlaying<-function(first, second, bin_width) {`
``` one<-data.frame(value=first) two<-data.frame(value=second)```
``` #here we apply an identity, so that when we bind them we know which is which one\$ident<-'first' two\$ident<-'second'```
``` #here we bind the two datasets so that we have one (this is why we needed the identities)```
``` myvalues<-rbind(one, two)```
``` final<-ggplot(myvalues, aes(value, colour="black", fill = ident)) + geom_histogram(alpha = 0.5, aes(y = ..density..), position = 'identity', binwidth=bin_width) plot(final) return(final) }```

Using this function, you will be able to have in one plot two overlayed histograms of your two values. In the input of the function, the “first” and “second” should be the two columns of data you want to overlay (which can be in the format “mydata1\$mycolumn1”, “mydata2\$mycolumn2” etc) and the “bin_width” corresponds to the binwidth of the histograms.

What we do, is, first, we create two data sets with only one column named “value”, containing our values. Then, we give an identity column in each of our datasets. Then we bind together our two datadets (now the new data set has two columns, one named “value” and one that holds the identity of each, sort of like melting them together). Now, we normally make a histogram of our new binded dataset, that fills each value according to its identity!

For this function to work, you will need the package ggplot2

note: this is part of my coursework in the module gis&science of my mres course 