在ggplot中从不平衡数据创建重叠直方图

时间:2015-05-26 20:48:13

标签: r ggplot2

我在R中使用ggplot2来绘制多个重叠的直方图。我见过这样的其他答案:

ggplot(histogram, aes(f0)) + 
geom_histogram(data = lowf0, fill = "red", alpha = 0.2) + 
geom_histogram(data = mediumf0, fill = "blue", alpha = 0.2) +
geom_histogram(data = highf0, fill = "green", alpha = 0.2)

如果我的数据来自相同长度的矢量但是它们不是,那么这将完美地工作。我目前有这个设置来创建两个单独的图,每个图使用两个不同的单矢量数据帧。我看了一遍,但一直找不到任何大小不同的数据

2 个答案:

答案 0 :(得分:1)

您可以构建数据,以便拥有包含该级别的列。然后ggplot有一个分组选项

times=c(10, 20, 30)
dat <- data.frame(levs=rep(c("low", "med", "high"), times=times),
                  counts=rexp(60, rate=c(rep(c(0.1, 0.2, 0.3), times=times))))
ggplot(dat, aes(counts, fill=levs, group=levs)) + 
    geom_histogram(position="dodge", alpha=0.2)

重叠密度可能看起来更好

ggplot(dat, aes(counts, fill=levs, group=levs)) + 
    geom_density(alpha=0.2)

答案 1 :(得分:1)

试试这个

ggplot(mapping = aes(f0)) + 
geom_histogram(data = histogram, fill = "red", alpha = 0.2) + 
geom_histogram(data = lowf0, fill = "red", alpha = 0.2) + 
geom_histogram(data = mediumf0, fill = "blue", alpha = 0.2) +
geom_histogram(data = highf0, fill = "green", alpha = 0.2)

如果您最初没有指定数据,则应该能够包含不同长度的数据。