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?

enter image description here

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

Answer

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

enter image description here

Attribution
Source : Link , Question Author : kodi1911 , Answer Author : hrbrmstr

Leave a Comment