[R] converting histogram to barchart

Thomas Fröjd tfrojd at gmail.com
Wed Apr 22 10:56:51 CEST 2009


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])

}




More information about the R-help mailing list