如何在直方图中添加每个条形顶部每个条形的计数或频率文本?

时间:2016-06-06 12:04:29

标签: r panel lattice

speed = factor(rep(c(6,8,9),4))
carbon = factor(rep(c(0.77,0.78),6))
Torsion = factor(rep(c("OK", "NotOK"),c(8,4)))
library(lattice)
histogram(~Torsion|speed*carbon, layout = c(6,1),type = "count")

在上面的示例中,我想在直方图的每个条形图的顶部添加以下文本“每个条形的频率”。我该怎么做呢?我用谷歌搜索但找不到合适的解决方案。

1 个答案:

答案 0 :(得分:0)

我按如下方式重写panel.histogram,并手动调整y轴限制以使标签适合(我确定可以自动调整)。

panel_histtext <- function(x, breaks, equal.widths = TRUE, type = "density",
                           nint = round(log2(length(x)) + 1),
                           alpha = plot.polygon$alpha, col = plot.polygon$col,
                           border = plot.polygon$border,      
                           lty = plot.polygon$lty, lwd = plot.polygon$lwd, 
                           labels, ...,
                           identifier = "histogram") {
    plot.polygon <- trellis.par.get("plot.polygon")
    xscale <- current.panel.limits()$xlim
    panel.lines(x = xscale[1] + diff(xscale) * c(0.05, 0.95), 
                y = c(0, 0), col = border, lty = lty, lwd = lwd, alpha = alpha, 
                identifier = paste(identifier, "baseline", sep = "."))
    if (length(x) > 0) {
      if (is.null(breaks)) {
        breaks <- if (is.factor(x)) 
          seq_len(1 + nlevels(x)) - 0.5
        else if (equal.widths) 
          do.breaks(range(x, finite = TRUE), nint)
        else quantile(x, 0:nint/nint, na.rm = TRUE)
      }
      h <- lattice:::hist.constructor(x, breaks = breaks, ...)
      y <- switch(type, count = h$counts, percent = 100 * h$counts/length(x), 
                  density = h$density)
      breaks <- h$breaks
      nb <- length(breaks)
      if (length(y) != nb - 1) 
        warning("problem with 'hist' computations")
      if (nb > 1) {
        panel.rect(x = breaks[-nb], y = 0, height = y, width = diff(breaks), 
                   col = col, alpha = alpha, border = border, lty = lty, 
                   lwd = lwd, just = c("left", "bottom"),
                   identifier = identifier)
        panel.text(x = breaks[-nb] + diff(breaks) / 2, y = y,
                   pos = 3, labels = as.character(y))
      }
    }
  }

然后使用新的面板功能绘制图表:

histogram(~ Torsion | speed * carbon, layout = c(6, 1), type = "count",
          ylim = c(0, 2.3),
          panel = function(x, ...) {
            panel.histogram(x, ...)
            panel_histtext(x, ...)
          })

Imgur