R 将此直方图中的计数更改为概率
我正在努力在不弄乱红色区域的情况下,将计数更改为下面直方图中的概率。另外,如何将1,10与x轴上的其余数字对齐R 将此直方图中的计数更改为概率,r,ggplot2,histogram,R,Ggplot2,Histogram,我正在努力在不弄乱红色区域的情况下,将计数更改为下面直方图中的概率。另外,如何将1,10与x轴上的其余数字对齐 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::scient
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)
ggplot(df,aes(x)) +
geom_histogram(binwidth=bw, color="white", fill = "#1380A1") +
geom_histogram(data=df %>% filter(x < 10^(-1) + 1.15*bw), binwidth=bw, color="white", fill = "red") +
geom_density(aes(y = bw*after_stat(count)), color="blue") +
scale_x_continuous(trans="log10", breaks = 10^seq(-1, 5, by = 1), labels = scientific)
库(dplyr)
图书馆(tibble)
图书馆(GG2)
nrep=10000
scientific您需要将层中的比例从计数更改为密度geom\u直方图
。在第一个柱状图中,您可以使用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)
很遗憾,我无法复制您的代码。要将geom\u直方图
从计数转换为密度,需要将y=after\u stat(density)
添加到aes()。然后,您可以使用fill
条件突出显示aes()中直方图的一部分。见@atsyplenkov谢谢。我编辑了代码。现在应该可以用了,谢谢。您知道如何将x轴上的1和10与其余数字对齐吗?当我将10^0和10^1更改为1和10时,它们的位置略高于其他标记。我认为将选定标记的标签放置在与x轴的整体标签对齐方式不同的对齐方式中是不可行的。
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)