[R] how to make a histogram with percentage on top of each bar?

Deepayan Sarkar deepayan.sarkar at gmail.com
Fri Jun 22 10:06:36 CEST 2012


On Thu, Jun 21, 2012 at 10:56 PM, york8866 <yu_york at hotmail.com> wrote:
> I have a dataset like the following:
> ID      DV
> 1       0.868576818
> 2       0.337120116
> 3       0.029233775
> 4       0.719783525
> 5       0.976631182
> 6       0.672941605
> 7       0.13239462
> 8       0.99936475
> 9       0.91540604
> 10      0.545686514
>
> to get a histogram with y axis as percentage, I wrote the following code"
> library(lattice)
> histogram(data)
>
> now , how to input the percentage and cumulative percentage on top of each
> bar?

You will need a custom panel function, along the lines of

mypanel <-
    function(x, breaks, nint = round(log2(length(x)) + 1), ...)
{
    if (missing(breaks))
        breaks <- do.breaks(range(x, finite = TRUE), nint)
    panel.histogram(x, breaks = breaks, ...)
    h <- hist(x, breaks = breaks, plot = FALSE)
    breaks <- h$breaks
    nb <- length(breaks)
    yy <- 100 * h$counts / length(x)
    panel.text(x = (breaks[-1] + breaks[-nb])/2, y = yy,
               labels = round(cumsum(yy), 2), pos = 3)
}

histogram(data, panel = mypanel)

-Deepayan



More information about the R-help mailing list