【问题标题】:Weird behavior in ggplotggplot 中的奇怪行为
【发布时间】:2023-02-05 03:42:12
【问题描述】:

我正在使用Ecdat 库中的数据集PatentsRD,遇到了ggplot 的奇怪行为,我没有任何解释。

我绘制了两个函数泊松分布(一次使用公式,一次使用dpois)以查看它们是否实际上相同:

library(tidyverse)
library(Ecdat)
data(PatentsRD)

plot <- ggplot(data = data.frame(x = c(0:100)), aes(x = x))+
  stat_function(fun = function(x){(mean(PatentsRD$patent)^x)/(factorial(x))*exp(-mean(PatentsRD$patent))}, color = "red")+
  stat_function(fun = function(x){dpois(x, mean(PatentsRD$patent))}, color = "green")
plot

很好,两个功能完全一样。但是当我现在尝试添加数据的密度函数时,事情变得一团糟:

plot +
  geom_density(data = PatentsRD, aes(x = patent))

为什么绿色和红色函数突然不再相等了?绿色和红色都不再具有正确的高度(略高于 0.05)。这里发生了什么?

【问题讨论】:

    标签: r ggplot2 visualization


    【解决方案1】:

    这里的问题是stat_function 计算沿 x 轴固定数量的点的 y 值。当您添加密度图时,x 轴范围会急剧增加,因此曲线的分辨率会下降。对于红色曲线,这意味着函数恰好不是在精确的峰值处计算的(并且看起来不再平滑)。

    绿色曲线的情况更糟,因为dpois 返回带有警告的非整数值 0,因此根本无法正确评估绿色曲线。

    要解决分辨率问题,请增加 stat_function 中的 n 参数(默认值为 x 轴上的 101 个样本)。

    要修复绿色曲线,请在 round(x) 而不是 x 处求值:

    ggplot() +
      stat_function(fun = function(x){
        (mean(PatentsRD$patent)^x)/(factorial(x))*exp(-mean(PatentsRD$patent))
        }, color = "red", n = 1000)+
      stat_function(fun = function(x){dpois(round(x), mean(PatentsRD$patent))}, 
                    color = "green", n = 1000) +
      geom_density(data = PatentsRD, aes(x = patent))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-22
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-07
      • 2018-11-06
      相关资源
      最近更新 更多