ggplot2直方图与不同变量重叠 [英] Overlapping ggplot2 histograms with different variables
本文介绍了ggplot2直方图与不同变量重叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有2个不同的变量要绘制为直方图,该怎么办?举个例子:
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)
如果我想在同一图中绘制data1和data2的直方图,有办法吗?
If I want histograms of data1 and data2 in the same plot, is there a way of doing it?
推荐答案
只需添加另一个 geom_histogram
层,即可在同一图中获得它们:
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))
或方面:
##My preference
ggplot(d) +
geom_histogram(aes(x=x)) +
facet_wrap(~type)
或使用条形图(感谢@rawr)
or using barplots (thanks to @rawr)
ggplot(d, aes(x, fill = type)) +
geom_bar(position = 'identity', alpha = .5)
这篇关于ggplot2直方图与不同变量重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文