0

How to plot histogram and density of values in the same plot and same levels: that is that density plot should be as "high" as histogram

library(ggplot2)
LONG <- c(runif(20000,-10.8544921875,-9.021484375))
LONG = data.frame(LONG)
ggplot(LONG, aes(LONG, ..count..)) + geom_histogram(fill = "steelblue") + 
  geom_density()

Is not working and density is much more bigger than I want it to be

Petr
  • 1,606
  • 2
  • 14
  • 39
  • This does not answer my question _ I want Histogram to be "High" to aprox. 700 units and Density plot to have same height and be in the same scale as Histogram in example script. – Petr Nov 20 '19 at 12:11
  • Not a duplicate question - I want to account also for scalling. – Petr Nov 20 '19 at 12:17
  • 1
    I tried Ramnath's solution in the linked question and it shows the empirical density in the "same scale as the histogram". What exactly does not meet your requirements? The density will always be smoother than the bars, so its max value will not be exactly the max value of the bars. If you want arbitrary scaling, multiply `..density..` by a factor that suits you in the `aes()` definition. – cymon Nov 20 '19 at 12:46
  • 1
    You can only match the kde and histogram if you know the binwidth of the histogram, e.g. `binwidth <- 0.1`. Then, you could plot as follows: `ggplot(LONG, aes(LONG)) + geom_histogram(fill = "steelblue", binwidth = binwidth) + geom_density(aes(y = stat(count) * binwidth))` – teunbrand Nov 20 '19 at 14:22

0 Answers0