Overlapping ggplot2 histograms with different variables

断了今生、忘了曾经 提交于 2021-02-04 07:49:13

问题


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: enter image description here



来源:https://stackoverflow.com/questions/23480248/overlapping-ggplot2-histograms-with-different-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!