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

标签 r ggplot2 probability-density

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

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

enter image description here

有没有一种方法可以根据这两个正偏的离散相关变量来计算每个组合(例如 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))

enter image description here

此处运行密度并转换为与数据具有相同坐标的小标题。 (有没有更好的方法来做到这一点?)

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)

enter image description here

关于r - 根据 R 中的二维密度图计算值的概率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59507974/

相关文章:

python - 在Python中生成指数分布

c++ - 引用其他对象作为引用类字段

r - geom_boxplot,如何根据组专门为异常值着色并保持黑色?

r - 使用facet_wrap将r平方注释为ggplot

ggplot2 - 使用pyspark+databricks时如何绘制相关热图

c++ - 将概率分布拟合到观察到的数据c++

python - 是否有计算不同类型概率密度函数积分的捷径?

r - 如何在 dplyr 中使用链接来访问 "internal"变量

python - Python 中的 Kendall 一致性系数 (W)

r - Azure Notebooks 中插入符号包安装失败且退出状态为非零