[R] Generating a Special Histogram
Duncan Murdoch
murdoch.duncan at gmail.com
Thu Jan 5 17:47:16 CET 2017
On 05/01/2017 11:01 AM, Dan Abner wrote:
> Hi all,
>
> Is anyone aware of a package, function, or general R trick that would make
> generating histograms like the one in the attachment easy in R (i.e.,
> without manually drawing each individual horizontal line and specifying the
> coordinates for a textbox for each number)?
>
> I need to make ~12 of these for different samples of n=25, so the manual
> approach would be very painful...
You can write a function to do this pretty easily. hist(...,
plot=FALSE) does all the calculations for you; you just need to write
the loop to draw the boxes. For example,
myhist <- function(x) {
histvals <- hist(x, plot = FALSE)
with(histvals, {
plot(range(breaks), range(c(0, counts)), type = "n")
for (i in seq_along(histvals$counts)) {
keep <- (breaks[i] < x & x <= breaks[i+1]) |
(i == 1 & x == breaks[1])
vals <- x[keep]
for (j in seq_along(vals)) {
rect(breaks[i], j-1, breaks[i+1], j)
text(mids[i], j-0.5, vals[j])
}
}
})
}
x <- round(rnorm(20, mean=166, sd=4))
myhist(x)
Duncan Murdoch
More information about the R-help
mailing list