[R] converting histogram to barchart

Kingsford Jones kingsfordjones at gmail.com
Thu Apr 23 05:24:58 CEST 2009


Hi Thomas,

Here's a simple example of adding a KDE line to a plotted histogram:

set.seed(222)
x <- rnorm(100)
hist(x, freq=FALSE)
lines(density(x), lty=2, col=2, lwd=2)

Note the need to set the freq to FALSE -- otherwise hist will
calculate counts within bins rather than probability densities.  Also,
you may need to adjust the ylim and xlim arguments if the densities
from your two samples are dissimilar.

As for converting the histogram to a bar plot -- I think that's an
aberration best left in Excel...

hope it helps,

Kingsford Jones


On Wed, Apr 22, 2009 at 2:56 AM, Thomas Fröjd <tfrojd at gmail.com> wrote:
> Hi list,
>
> After a lot of tweaking i have managed to create a histogram with an
> overlaying density plot. The histogram shows a sample of birth weights
> of babies and the density plot shows birth weights from a much larger
> reference populaton. My data is divided in 0.1 Kg bins so in the code
> below binweigh=0.1.
>
> The trouble with the current graph is that it is not very clear since
> the density plot overlay the histogram and obfuscates it. My plan to
> fix this is to convert the histogram to a barplot, basically the same
> thing but with space between the histogram bars and then plotting
> density with a line instead of a filled area. I have however failed so
> far.
>
> Could anyone give me a few tips? There is basically two things to solve.
>
> 1. Covert histogram to a barplot
> 2. Convert polygon to line.
>
> Here is the code so far with comments. weights$Weight is the
> individual weight observations.
>
> Best regards.
>
>
> # calucate the right breakpoints
> breakpoints <- seq(min(weights), max(weights), by=binwidth)
>
> #scale density
> dens <- density(reference)
> dens$y <- dens$y * (length(weights$Weight)*binwidth)
>
> #graph it
> hist(weights$Weight, freq=TRUE, breaks=breakpoints, xlab=xlabel,
> ylab="No of Births",  main=titles[i])
> polygon(dens$x, dens$y, border=NA, col="grey60")
>
> #direct into open device
> par(new=T)
>
> #histogram
> hist(weights$Weight, freq=TRUE, breaks=breakpoints, xlab=xlabel,
> ylab="No of Births",  main=titles[i])
>
> }
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list