I need to align the density line with the height of geom_histogram and keep count values on the y axis instead of density.
I have these 2 versions:
# Creating dataframe
library(ggplot2)
values <- c(rep(0,2), rep(2,3), rep(3,3), rep(4,3), 5, rep(6,2), 8, 9, rep(11,2))
data_to_plot <- as.data.frame(values)
# Option 1 ( y scale shows frequency, but geom_density line and geom_histogram are not matching )
ggplot(data_to_plot, aes(x = values)) +
geom_histogram(aes(y = ..count..), binwidth = 1, colour= "black", fill = "white") +
geom_density(aes(y=..count..), fill="blue", alpha = .2)+
scale_x_continuous(breaks = seq(0, max(data_to_plot$values), 1))
y scale shows frequency, but geom_density line and geom_histogram are not matching
# Option 2 (geom_density line and geom_histogram are matching, but y scale density = 1)
ggplot(data_to_plot, aes(x = values)) +
geom_histogram(aes(y = after_stat(ndensity)), binwidth = 1, colour= "black", fill = "white") +
geom_density(aes(y = after_stat(ndensity)), fill="blue", alpha = .2)+
scale_x_continuous(breaks = seq(0, max(data_to_plot$values), 1))
geom_density line and geom_histogram are matching, but y scale density = 1
What I need is plot from Option 2, but Y scale from Option 1. I can get it by adding (aes(y=1.25*..count..)
for this particular data, but my data is not static and this will not work for another dataset (just modify values
to test):
# Option 3 (with coefficient in aes())
ggplot(data_to_plot, aes(x = values)) +
geom_histogram(aes(y = ..count..), binwidth = 1, colour= "black", fill = "white") +
geom_density(aes(y=1.25*..count..), fill="blue", alpha = .2)+
scale_x_continuous(breaks = seq(0, max(data_to_plot$values), 1))
Desired result: y scale shows frequency and geom_density line is matching with geom_histogram height
I cannot hardcode coefficient or bins.
This problem is close to the ones discussed here, but it did not work for my case:
Programatically scale density curve made with geom_density to similar height to geom_histogram?
How to put geom_density and geom_histogram on same counts scale