简体   繁体   中英

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?

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)

A slight variation and addition to @csgillespie's answer:

ggplot(d) + 
  geom_density(aes(x=x, colour=type, fill=type), alpha=0.5)

which gives:在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM