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)