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



我在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)

如果我的数据来自相等长度的向量,这将完美地工作,但它们不是。我目前已经设置了使用两个不同的单向量数据帧来创建两个单独的地块。我已经看遍了,但一直无法找到任何不同大小的数据

你可以构造你的数据,这样你就有一个包含关卡的列。那么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)

试试这个

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)

如果你一开始没有指定数据,你应该能够包含不同长度的数据

最新更新