Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overlaying histograms with ggplot2 in R

Tags:

r

ggplot2

I am new to R and am trying to plot 3 histograms onto the same graph. Everything worked fine, but my problem is that you don't see where 2 histograms overlap - they look rather cut off.

When I make density plots, it looks perfect: each curve is surrounded by a black frame line, and colours look different where curves overlap.

Can someone tell me if something similar can be achieved with the histograms in the 1st picture? This is the code I'm using:

lowf0 <-read.csv (....)
mediumf0 <-read.csv (....)
highf0 <-read.csv(....)
lowf0$utt<-'low f0'
mediumf0$utt<-'medium f0'
highf0$utt<-'high f0'
histogram<-rbind(lowf0,mediumf0,highf0)
ggplot(histogram, aes(f0, fill = utt)) + geom_histogram(alpha = 0.2)
like image 428
Bloomy Avatar asked Oct 17 '22 15:10

Bloomy


People also ask

How do you overlay two histograms in R?

Plot two histograms If you have a histogram object, all the data you need is contained in that object. Using plot() will simply plot the histogram as if you'd typed hist() from the start. However, you can now use add = TRUE as a parameter, which allows a second histogram to be plotted on the same chart/axis.

Can you build a histogram using ggplot2?

You can also make histograms by using ggplot2 , “a plotting system for R, based on the grammar of graphics” that was created by Hadley Wickham.

How do you overlay multiple histograms in the same plot?

To make multiple overlapping histograms, we need to use Matplotlib pyplot's hist function multiple times. For example, to make a plot with two histograms, we need to use pyplot's hist() function two times. Here we adjust the transparency with alpha parameter and specify a label for each variable.


1 Answers

Using @joran's sample data,

ggplot(dat, aes(x=xx, fill=yy)) + geom_histogram(alpha=0.2, position="identity")

note that the default position of geom_histogram is "stack."

see "position adjustment" of this page:

geom_histogram documentation

like image 296
kohske Avatar answered Oct 19 '22 04:10

kohske