Skip to content
Prev 381297 / 398502 Next

Creating a histogram from a frequency vector

hist() generates a histogram object that it then plots.

You can use your frequency vector to generate the same kind of object and then just plot it, though you'll have to provide breaks (possibly defaulted, if they're just 0:length(frequencies) ) and you'd have to work on the density component a bit.

I'm sure this is out there somewhere already, but here's as an example, using values pulled from a (nonequidistant) ?hist example and using a short off-the-cuff function to build the histogram object:

freqs <- c(11, 19,  5,  3,  2,  1,  0,  0,  2,  3,  2) #islands
brks <- c(4*0:5, 10*3:5, 70, 100, 140)

freqhist <- function(counts, xname=deparse(substitute(frequencies)), breaks=0:length(frequencies), 
	mids=(breaks[-1]+breaks[-length(breaks)])/2 , ...){
	
	binwidths <- diff(breaks) #This copes with unequal break intervals
	dens <- counts/(binwidths*sum(counts))

	retval <- structure(list(breaks=breaks, counts=counts,, density=dens, mids=mids, xname=xname, equidist=all(diff(breaks)==diff(breaks[1:2]) ),
		class="histogram")
}

plot(freqhist(freqs, breaks=brks))

#Also works equidistant with default 0:length(counts) breaks:

f2 <- c(30, 39, 31, 29, 10,  6,  3,  1,  0,  1)
plot(freqhist(f2))

Steve Ellison





*******************************************************************
This email and any attachments are confidential. Any use...{{dropped:8}}