如何创建镜像直方图

ECI*_*CII 7 plot r

我想在两组上显示倾向得分匹配统计数据(BW中无法比拟,颜色匹配),并希望使用像下面这样的镜像直方图

是否可以在基础R中叠加4个不同的直方图?有没有提供此功能的包?

x轴是[0,1]有界的(它是一个概率),BW列总是大于或等于彩色列(即彩色列后面不能有BW列).

图片来自http://www.ncbi.nlm.nih.gov/pubmed/22244556

day*_*yne 9

您可以使用以下内容.您可能希望预先计算hist对象以获取正确的ylim值,然后使用axismtexttitle正确标记图形.

set.seed(1234)
x <- rnorm(100, 0, 1)

plot.new()
plot.window(ylim = c(-40, 40), xlim = range(x))
p <- list(axes = FALSE, xlab = "", ylab = "", main = "")
par(new = TRUE)  
do.call(hist, c(list(x = x, ylim = c(-40, 40)), p))
par(new = TRUE)
do.call(hist, c(list(x = x, ylim = c(40, -40)), p))
axis(side = 2, 
     at = pretty(par()$usr[3:4]), 
     labels = abs(pretty(par()$usr[3:4])))
axis(side = 1)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

编辑

## Create some fake data
set.seed(1234)
d <- rnorm(250, 0, 1)
e <- rnorm(250, 1, 1)
f <- rlnorm(100, 0, .2)
g <- rlnorm(100, 1, .2)

## Function for plotting
multhist <- function(..., bin.width, col, dir, xlab = NULL, ylab = NULL,
                     main = NULL) {

  vals <- list(...)
  vrng <- range(vals)

  brks <- seq(vrng[1] - abs(vrng[1]*0.1), 
              vrng[2] + abs(vrng[2]*0.1), 
              by = bin.width)

  yrng <- max(sapply(lapply(vals, hist, breaks = brks), "[[", "counts"))
  yrng <- 1.2*c(-1*yrng, yrng)

  plot.new()
  plot.window(ylim = yrng, xlim = vrng)

  addhist <- function(x, col, dir) {
    par(new = TRUE)  
    hist(x = x, ylim = dir*yrng, col = col, xlab = "", ylab = "", 
         main = "", axes = FALSE, breaks = brks)
  }

  mapply(addhist, x = vals, col = col, dir = dir)

  py <- pretty(yrng)
  py <- py[py >= yrng[1] & py <= yrng[2]]
  axis(side = 2, at = py, labels = abs(py))
  axis(side = 1)
  title(main = main, xlab = xlab, ylab = ylab)

}
Run Code Online (Sandbox Code Playgroud)

您可以为函数提供数值向量,以及相应颜色和方向的向量(1或-1).我没有对vals,col和dir的长度进行正式检查,但它非常直接.

## Use the function
multhist(d, e, f, g, bin.width = 0.5, 
         col = c("white", "white", "lightgreen", "darkgreen"), 
         dir = c(1, -1, 1, -1), xlab = "xlabel", ylab = "ylabel", 
         main = "title")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述