R – Plot probability with ggplot2 (not density)

ggplot2r

I'd like to plot data such that on y axis there would be probability (in range [0,1]) and on x-axis I have the data values. The data is contiguous (also in range [0,1]), thus I'd like to use some kernel density estimation function and normalize it such that the y-value at some point x would mean the probability of seeing value x in input data.

So, I'd like to ask:

a) Is it reasonable at all? I understand that I cannot have probability of seeing values I do not have in the data, but I just would like to interpolate between points I have using a kernel density estimation function and normalize it afterwards.

b) Are there any built-in options in ggplot I could use, that would override default behavior of geom_density() for example for doing this?

Thanks in advance,

Timo

EDIT:
when i said "normalize" before, I actually meant "scale". But I got the answer, so thanks guys for clearing up my mind about this.

Best Answer

Just making up a quick merge of @JD Long's and @yesterday's answers:

ggplot(df, aes(x=x)) +
  geom_histogram(aes(y = ..density..), binwidth=density(df$x)$bw) +
  geom_density(fill="red", alpha = 0.2) +
  theme_bw() +
  xlab('') +
  ylab('')

enter image description here

This way the binwidth for ggplot2 was calculated by the density function, and also the latter is drawn on the top of a histogram with a nice transparency. But you should definitely look into stat_densitiy as @yesterday suggested for further customization.

Related Topic