# R: geom_density values in y-axis [duplicate]

Why geom_density is showing me values higher than 1 in the density plot? How to change it into fraction?

And my code used to generate the plot

ggplot(data = input2, aes(x = r.close)) +
geom_density(aes(y = ..density.., fill = Próba), alpha = 0.3, stat = "density", position = "identity") +

xlab("y") + ylab("density") +
theme_bw() +
theme(plot.title=element_text(size = rel(1.6), face = "bold"),
legend.position = "bottom",
legend.background = element_rect(colour = "gray"),
legend.key = element_rect(fill = "gray90"),
axis.title = element_text(face = "bold", size = 13))

• geom_density(aes(y=..scaled..)) Sep 13 '15 at 16:36

Or you can just used the computed ..scaled.. value stat_density provides:

library(ggplot2)

set.seed(1)
vals1 <- rbeta(1000, 0.5, 0.1)
vals2 <- rbeta(1000, 0.25, 0.3)

gg <- ggplot(data.frame(x=c(vals1, vals2),
grp=c(rep("a", 1000), rep("b", 1000))))
gg <- gg + geom_density(aes(x=x, y=..scaled.., fill=grp), alpha=1/2)
gg <- gg + theme_bw()
gg


• Isn't the total area under the curve still higher than 1?
– Ben
Jul 6 '20 at 8:53

It looks like geom_density() is displaying the appropriate values. The area under that whole curve should be 1.

To get an estimate of the probability of certain values, you'd have to integrate over an interval on your 'y' axis, and that value should never be greater than 1.

• So, what is currently displayed as the y-axis and how to show the probability? Sep 13 '15 at 15:15
• Your y-axis is appropriately labeled - it is showing an approximate probability density curve for these data. A density curve can take on point values greater than one, but must be non-negative everywhere and the integral of the whole curve must be equal to one. Check out the Wikipedia article on probability density functions. If you need the y-axis to be less than one, try a histogram with geom_hist().
– user88719
Sep 13 '15 at 15:23
• @DavidKent Using a histogram (the correct geom is named geom_histogram(), BTW) won’t help. A histogram is still a density estimate, and can have y-values greater than 1. Sep 13 '15 at 15:59
• Ah, that makes sense - it'll still sum to one with aes(y=..density..). Would geom_histogram(aes(y=..count../N)) work? Then the height of each bin would be the proportion of values that are in the bin's range?
– user88719
Sep 13 '15 at 16:20