Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overlapping ggplot2 histograms with different variables

If I had 2 different variables to plot as histograms, how would I do it? Take an example of this:

data1 <- rnorm(100)
data2 <- rnorm(130)

If I want histograms of data1 and data2 in the same plot, is there a way of doing it?

like image 996
user3605505 Avatar asked Apr 21 '26 12:04

user3605505


1 Answers

You can get them in the same plot, by just adding another geom_histogram layer:

## Bad plot
ggplot() + 
  geom_histogram(aes(x=data1),fill=2) + 
  geom_histogram(aes(x=data2)) 

However, a better idea would be to use density plots:

d = data.frame(x = c(data1, data2), 
               type=rep(c("A", "B"), c(length(data1), length(data2))))
ggplot(d) + 
  geom_density(aes(x=x, colour=type))

or facets:

##My preference
ggplot(d) + 
  geom_histogram(aes(x=x)) + 
  facet_wrap(~type)

or using barplots (thanks to @rawr)

ggplot(d, aes(x, fill = type)) + 
  geom_bar(position = 'identity', alpha = .5)
like image 177
csgillespie Avatar answered Apr 24 '26 00:04

csgillespie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!