[R] barplot with a probability density curve

Jim Lemon jim at bitwrit.com.au
Mon Mar 15 07:43:25 CET 2010


On 03/15/2010 08:32 AM, Olga Lyashevska wrote:
> Dear all,
>
> I am making a barplot as following:
>
> barplot(c(1,2,3,5,2,3,1),names.arg=c("100","200","300","400","500","600","700"),xlab="diameter",ylab="flow",main="some title",space=0.1)
>
> I am also trying to add a probability density curve, however using
> lines(density(c(1,2,3,5,2,3,1))) does not give a desired result.
>
Hi Olga,
Part of your problem is that the barplot function places bars at 
positions along the abcissa that are not quite what you expect. These 
start at 0.6 and end at 7.2 with an increment of 1.1. The density 
function produces values that begin at -1.048 and end at 7.048, 
effectively shifting the density curve to the left.

As noted by other correspondents, the density function may not be what 
you want anyway. If you want a smoothed line that infers what might 
happen if flow for intermediate values of diameter were measured, you 
could try:

lines(spline(1:7,c(1,2,3,5,2,3,1),xmin=0,xmax=8))

The smoothed values are still a bit offset, so you might consider using:

library(plotrix)
barp(c(1,2,3,5,2,3,1),
  names.arg=c("100","200","300","400","500","600","700"),
  xlab="diameter",ylab="flow",main="some title",height.at=0:5)
lines(spline(1:7,c(1,2,3,5,2,3,1),xmin=0,xmax=8))

As the barp function places the bars at integer values, which happen to 
be convenient for this case, but also are easy to adjust if you used the 
real diameter values.

Jim



More information about the R-help mailing list