stat_density_2d
MASS::kde2d
在引擎盖下使用。我想有很多方法可以做到这一点,但我们可以将数据输入该函数并将其转换为整洁的数据,以获得该类型估计的平滑版本。
首先,一些像您这样的数据:
library(tidyverse)
set.seed(42)
df <- tibble(
R = rlnorm(1E4, 0, 0.2) * 100,
B = R * rnorm(1E4, 1, 0.2)
)
ggplot(df, aes(R,B)) +
geom_bin2d(binwidth = c(1,1))
在这里运行密度并转换为与数据具有相同坐标的小标题。(是否有更好的方法可以做到这一点?)
n = 201 # arbitrary grid size, chosen to be 1 more than the range below
# so the breaks are at integers
smooth <- MASS::kde2d(df$R, df$B, lims = c(0, 200, 0, 200),
# h = c(20,20), # could tweak bandwidth here
n = n)
df_smoothed <- smooth$z %>%
as_tibble() %>%
pivot_longer(cols = everything(), names_to = "col", values_to = "val") %>%
mutate(R = rep(smooth$x, each = n), # EDIT: fixed, these were swapped
B = rep(smooth$y, n))
df_smoothed
现在拥有R和B维度中所有从0:200开始的坐标,并具有val
列中每种组合的概率。这些加起来几乎等于1(在这种情况下为99.6%)。我认为剩余的smidgen是超出指定范围的坐标的概率。
sum(df_smoothed$val)
#[1] 0.9960702
任何特定组合的机会都只是该点的密度值。因此,R = 70和B = 100的机会是0.013%。
df_smoothed %>%
filter(R == 70, B == 100)
## A tibble: 1 x 4
# col val R B
# <chr> <dbl> <int> <int>
#1 V101 0.0000345 70 100
R在50-100之间和B在50-100之间的机会是36.9%:
df_smoothed %>%
filter(R %>% between(50, 100),
B %>% between(50, 100)) %>%
summarize(total_val = sum(val))
## A tibble: 1 x 1
#total_val
#<dbl>
# 1 0.369
以下是平滑数据和原始数据的外观:
ggplot() +
geom_tile(data = df_smoothed, aes(R, B, alpha = val), fill = "red") +
geom_point(data = df %>% sample_n(500), aes(R, B), size = 0.2, alpha = 1/5)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句