3

I am wanting to put geom_histogram and geom_density on the same scale. I can accomplish this in one direction by using geom_histogram(aes(y = stat(density))). This works great if I want everything on the density scale. However, I am wanting things on the count scale. But adding geom_density(aes(y = stat(count))) results in a density line that is not on the same scale as the counts in the histogram. Is there a way to get both density and histogram on the same count scale?

library(tidyverse)

df <- tibble(x = rnorm(10000))

ggplot(df, aes(x)) +
  geom_histogram(aes(y = stat(density))) +
  geom_density()
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

ggplot(df, aes(x)) +
  geom_histogram() +
  geom_density(aes(y = stat(count)))
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Created on 2019-05-01 by the reprex package (v0.2.1)

Jake Thompson
  • 2,591
  • 1
  • 16
  • 32
  • 1
    Possible duplicate of [geom_density to match geom_histogram binwitdh](https://stackoverflow.com/questions/37404002/geom-density-to-match-geom-histogram-binwitdh). Use `ggplot(df,aes(x))+ geom_histogram(binwidth = 0.5)+ geom_density(aes(y=0.5 * ..count..))` – c1au61o_HH May 01 '19 at 15:54
  • I know little about this, but look at this [link](https://stackoverflow.com/questions/17755265/how-do-i-change-the-kernel-bandwidth-used-in-a-density-plot-in-r) and try to change this argument `geom_density(aes(y = stat(count)), adjust = 25)`, if the above comment does not satisfy you. – bbiasi May 01 '19 at 16:00

0 Answers0