我需要将密度线与 geom_histogram 的高度对齐,并在 y 轴而不是密度上保留计数值。
我有这两个版本:
# 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)
Run Code Online (Sandbox Code Playgroud)
# 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))
Run Code Online (Sandbox Code Playgroud)
y 刻度显示频率,但 geom_密度线和 geom_histogram 不匹配

# Option 2 (geom_density line and geom_histogram …Run Code Online (Sandbox Code Playgroud)