根据 R 中的二维密度图计算值的概率

Calculate probability of value based on 2D density plot in R

我正在寻找一个函数来计算 B 和 R 的特定组合的可能性。数据的当前图示如下所示:

ggplot(df, aes(R,B)) +
geom_bin2d(binwidth = c(1,1))

有没有一种方法可以根据这两个正偏的离散相关变量来计算每个组合(例如 R = 23,B = 30)的概率?

是否可以使用stat_density_2d来解决或者有更好的方法吗?

谢谢。

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)

如果只是关于绘图,可以简单地关闭等高线并使用 geom = raster,就像建议的 in the ggplot2 reference 一样。

感谢@JonSpring 提供示例数据!

library(tidyverse)

df <- tibble(
  R = rlnorm(1E4, 0, 0.2) * 100,
  B = R * rnorm(1E4, 1, 0.2)
)

ggplot(df, aes(R,B)) +
  stat_density2d(geom = 'raster', aes(fill = stat(density)), contour = FALSE) 

reprex package (v0.3.0)

于 2019-12-28 创建