问题
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?
回答1:
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)
回答2:
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:
来源:https://stackoverflow.com/questions/23480248/overlapping-ggplot2-histograms-with-different-variables