2

我试图在一个图中绘制两个直方图,但是这两组的分布方式使得直方图有点难以解释。我的直方图现在看起来像这样:

在此处输入图像描述

这是我的代码:

hist(GROUP1, col=rgb(0,0,1,1/2), breaks=100, freq=FALSE,xlab="X",main="")  # first histogram
hist(GROUP1, col=rgb(1,0,0,1/2), breaks=100, freq=FALSE , add=T)  # second
legend(0.025,600,legend=c("group 1","group 2"),col=c(rgb(1,0,0,1/2),rgb(0,0,1,1/2)),pch=20,bty="n",cex=1.5)

是否可以绘制此直方图,使两组的条形图彼此相邻,而不是重叠?我意识到这可能会增加一些混乱,因为 X 轴代表一个连续变量......当然也欢迎其他关于如何使这个图更清晰的建议!

4

2 回答 2

8

与其搞乱重叠的直方图,不如:

  1. 在单独的面板中有两个直方图,即

    par(mfrow=c(1,2))
    d1 = rnorm(100);d2 = rnorm(100);
    hist(d1);hist(d2)
    
  2. 或者,使用密度图

    plot(density(d1))
    lines(density(d2), col=2)
    
  3. 或者结合使用密度图和直方图

    hist(d1, freq=FALSE)
    lines(density(d2), col=2)
    
于 2012-10-08T15:41:46.373 回答
6

你可以滥用barplot它:

multipleHist <- function(l, col=rainbow(length(l))) {
    ## create hist for each list element
    l <- lapply(l, hist, plot=FALSE);

    ## get mids
    mids <- unique(unlist(lapply(l, function(x)x$mids)))

    ## get densities
    densities <- lapply(l, function(x)x$density[match(x=mids, table=x$mids, nomatch=NA)]);

    ## create names
    names <- unique(unlist(lapply(l, function(x)x$breaks)))

    a <- head(names, -1)
    b <- names[-1]
    names <- paste("(", a, ", ", b, "]", sep="");

    ## create barplot list
    h <- do.call(rbind, densities);

    ## set names
    colnames(h) <- names;

    ## draw barplot
    barplot(h, beside=TRUE, col=col);

    invisible(l);
}

例子:

x <- lapply(c(1, 1.1, 4), rnorm, n=1000)
multipleHist(x)

一个图中的多个直方图

编辑: 这是一个像 OP 建议的那样绘制 x 轴的示例。恕我直言,这是非常具有误导性的(因为条形图的箱不是连续值)并且不应使用

multipleHist <- function(l, col=rainbow(length(l))) {
    ## create hist for each list element
    l <- lapply(l, hist, plot=FALSE);

    ## get mids
    mids <- unique(unlist(lapply(l, function(x)x$mids)))

    ## get densities
    densities <- lapply(l, function(x)x$density[match(x=mids, table=x$mids, nomatch=NA)]);

    ## create names
    breaks <- unique(unlist(lapply(l, function(x)x$breaks)))

    a <- head(breaks, -1)
    b <- breaks[-1]
    names <- paste("(", a, ", ", b, "]", sep="");

    ## create barplot list
    h <- do.call(rbind, densities);

    ## set names
    colnames(h) <- names;

    ## draw barplot
    barplot(h, beside=TRUE, col=col, xaxt="n");

    ## draw x-axis
    at <- axTicks(side=1, axp=c(par("xaxp")[1:2], length(breaks)-1))
    labels <- seq(min(breaks), max(breaks), length.out=1+par("xaxp")[3])
    labels <- round(labels, digits=1)
    axis(side=1, at=at, labels=breaks)

    invisible(l);
}

一个图中的多个直方图(修改的 x 轴)

请在github上找到完整的源代码。

于 2012-10-08T15:50:01.613 回答