Вам необходимо изменить масштаб от подсчета до плотности в слоях geom_histogram
. На первой гистограмме вы можете сделать это, используя after_stat(density)
, что эквивалентно after_stat(count/sum(count))/bw
. Однако та же самая процедура не работает во второй гистограмме, потому что sum(count)
отличается, когда вы задаете поднабор данных. Если вы это сделаете, вторая гистограмма будет в другом масштабе.
library(dplyr)
library(tibble)
library(ggplot2)
nrep = 10000
scientific <- function(x){
ifelse(x==1e+0, "1", ifelse(x==1e+1,"10",parse(text=gsub("[+]", "", gsub("1e+", "10^", scales::scientific_format()(x))))))
}
bw <- 0.05
mx=rf(nrep,5,2)
df = tibble(x = mx)
pdf <- df %>% filter(x < 10^(-1) + 1.15*bw)
ggplot() +
geom_histogram(data = df,
aes(x = x, y = after_stat(count/sum(count)/bw),
binwidth=bw, color="white", fill = "#1380A1") +
geom_histogram(data = pdf,
aes(x = x, y = after_stat(count/sum(count)/bw),
binwidth=bw, color="white", fill = "red") +
geom_density(data = df,
aes(x = x), color="blue") +
scale_x_continuous(trans="log10", breaks = 10^seq(-1, 5, by = 1),
labels = scientific)

Следовательно, вам нужно рассчитать плотность с тем же знаменатель из первой гистограммы, который определяется как nrep
.
library(dplyr)
library(tibble)
library(ggplot2)
nrep = 10000
scientific <- function(x){
ifelse(x==1e+0, "1", ifelse(x==1e+1,"10",parse(text=gsub("[+]", "", gsub("1e+", "10^", scales::scientific_format()(x))))))
}
bw <- 0.05
mx=rf(nrep,5,2)
df = tibble(x = mx)
pdf <- df %>% filter(x < 10^(-1) + 1.15*bw)
ggplot() +
geom_histogram(data = df,
aes(x = x, y = after_stat(density)),
binwidth=bw, color="white", fill = "#1380A1") +
geom_histogram(data = pdf,
aes(x = x, y = after_stat(count/nrep)/bw),
binwidth=bw, color="white", fill = "red") +
geom_density(data = df,
aes(x = x), color="blue") +
scale_x_continuous(trans="log10", breaks = 10^seq(-1, 5, by = 1),
labels = scientific)
