You have three problems:
i) Barplot's plot locations are not at 100-700 in your picture.
ii) density applied to your bar hights will produce the density as if
those are x locations, not heights.
iii) density's height is scaled to unit area and not the height of your
And a statistical issue: barplot typically plots heights for a
categorical list of separate groups, while density assumes that x and y
are pretty much continuous interval scale quantities. Combining the two
would not generally have any useful meaning.
So the bad news is that not a lot of what you're doing is right.
That isn't very helpful, so I'm going to guess at what you might be
trying to do. A thing which _would_ have some useful meaning is a
combination of a histogram (special case of bar plot) and a density
Let's say you had data like this:
(I've guessed at your actual values just for illustration; usually x
would not be simple integer multiples of 100, but it shows the
Then you could do
hist(x, breaks=seq(50,750,100), freq=FALSE)
The freq=FALSE tells the histogram to scale for unit area so the density
line can be compared with the histogram heights.
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.
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
The smoothed values are still a bit offset, so you might consider using:
Thanks everyone for your kind responses.
Now I understand what is gong on! I guess that the question asked is
wrong in the first place.
As there is a categorical list of groups and their values (a range of
pipe diameters and a flow for each diameter), and a barplot would be a
suitable tool to use.
However, it also means that I cannot plot probability density curve
using this type of data because I would need to have a histogram
instead. Did I get it right?
> On 03/15/2010 08:32 AM, Olga Lyashevska wrote:
>> Dear all,
>> I am making a barplot as following:
>> 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.