【问题标题】:ggplot add Normal Distribution while using `facet_wrap` [duplicate]ggplot在使用`facet_wrap`时添加正态分布[重复]
【发布时间】:2021-05-01 14:21:24
【问题描述】:

我希望绘制以下直方图:

library(palmerpenguins)
library(tidyverse)

penguins %>% 
  ggplot(aes(x=bill_length_mm, fill = species)) +
  geom_histogram() + 
  facet_wrap(~species)

对于每个直方图,我想为每个直方图添加一个正态分布,其中包含每个物种的平均值和标准差。

当然,我知道我可以在开始使用 ggplot 命令之前计算组特定平均值和 SD,但我想知道是否有更智能/更快的方法来执行此操作。

我试过了:

penguins %>% 
  ggplot(aes(x=bill_length_mm, fill = species)) +
  geom_histogram() + 
  facet_wrap(~species) + 
  stat_function(fun = dnorm)

但这只会在底部给我一条细线:

有什么想法吗? 谢谢!

编辑 我想我要重新创建的是来自 Stata 的这个简单命令:

hist bill_length_mm, by(species) normal

这给了我这个:

我明白这里有一些建议:using stat_function and facet_wrap together in ggplot2 in R

但我专门寻找一个不需要我创建单独函数的简短答案。

【问题讨论】:

  • 你需要计算这个。尝试手动计算dnorm(penguins$bill_length_mm) - 你会发现可笑 小数字(大约-300 的幂!)。我想您需要先将它们装箱才能理解该 dnorm 调用。四舍五入没有帮助,所以我不认为它(仅仅是)一个浮点问题
  • 谢谢 - 我会试试的。我添加了促使我从 Stata 尝试这个的数字。当然,数据会转换为密度

标签: r ggplot2


【解决方案1】:

不久前,我用我写的 ggh4x 包中的一个函数自动绘制了这个理论密度图,你可能会觉得这很方便。您只需确保直方图和理论密度处于相同的比例(例如每个 x 轴单位的计数)。

library(palmerpenguins)
library(tidyverse)
library(ggh4x)

penguins %>% 
  ggplot(aes(x=bill_length_mm, fill = species)) +
  geom_histogram(binwidth = 1) + 
  stat_theodensity(aes(y = after_stat(count))) +
  facet_wrap(~species)
#> Warning: Removed 2 rows containing non-finite values (stat_bin).

您可以改变直方图的 bin 大小,但也必须调整理论密度计数。通常你会乘以 binwidth。

penguins %>% 
  ggplot(aes(x=bill_length_mm, fill = species)) +
  geom_histogram(binwidth = 2) + 
  stat_theodensity(aes(y = after_stat(count)*2)) +
  facet_wrap(~species)
#> Warning: Removed 2 rows containing non-finite values (stat_bin).

reprex package (v0.3.0) 于 2021-01-27 创建

如果这太麻烦,您可以随时将直方图转换为密度,而不是将密度转换为计数。

penguins %>% 
  ggplot(aes(x=bill_length_mm, fill = species)) +
  geom_histogram(aes(y = after_stat(density))) + 
  stat_theodensity() +
  facet_wrap(~species)

【讨论】:

  • 我有点期待你的 ggh4x 也有一个统计数据:)
  • 整个软件包的主要动机是“让我感到沮丧的事情应该更容易”:)
  • 确实,这太棒了!期待在 CRAN 上看到这个!
  • 你太客气了。我可能应该在某个时候!
  • 绝对同意,非常有用的包
【解决方案2】:

虽然ggh4x 包是在这种情况下要走的路,但更通用的方法是使用tapply 并使用PANEL 变量,该变量在应用构面时添加到数据中。

penguins %>% 
  ggplot(aes(x=bill_length_mm, fill = species)) +
  geom_histogram(aes(y = after_stat(density)), bins = 30) + 
  facet_wrap(~species) + 
  geom_line(aes(y = dnorm(bill_length_mm,
                          mean = tapply(bill_length_mm, species, mean, na.rm = TRUE)[PANEL],
                          sd = tapply(bill_length_mm, species, sd, na.rm = TRUE)[PANEL])))

【讨论】:

  • 非常感谢您提供的非常有用的补充。我不知道PANEL 变量,我需要继续阅读!恐怕由于与此问题的某些关系,该问题已关闭:stackoverflow.com/questions/1376967/… 也许也在那里分享您的解决方案! :)
  • 为什么不用species 而不是PANELPANEL 只是没有标签的species
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-16
  • 1970-01-01
  • 2011-12-28
相关资源
最近更新 更多