如何在 r 中将 geom_bar 和 dpois stat_function 合并在一起?

How do I merge a geom_bar and a dpois stat_function together in r?

我正在尝试在 r 中合并我的 2 个地块。我目前有 2 个这样的 ggplots:

ggplot(dataset2, aes(x = factor(V1))) +
    geom_bar(alpha = 0.2)
    
ggplot(dataset2, aes(V1)) +
    stat_function(geom="line", n=10, fun=dpois, args=list(1.602))

这给了我情节: bar plot 和 dpois plot.

我正在尝试将它们合并成这样的东西 merged plot。
我试过像这样将 stat_function 添加到第一个 ggplot:

    ggplot(dataset2, aes(x = factor(V1))) +
      geom_bar(alpha = 0.2) +
      stat_function(geom="line", n=10, fun=dpois, args=list(1.602))

但这给了我情节 plot of flat-lined dpois。

如何创建一个图表,使两个图表看起来像它们单独做的那样?

您需要转换其中一个几何图层,使其与另一个几何图层处于同一比例,然后添加辅助轴:

ggplot(dataset2, aes(x = V1)) +
  geom_bar(alpha = 0.2, aes(y = after_stat(count)/nrow(dataset2))) +
  stat_function(geom="line", fun = dpois, n = 11, args = list(1.602)) +
  scale_y_continuous(name = "Density",
                     sec.axis = sec_axis(~.x*nrow(dataset2), name = "Count"))


使用的数据

set.seed(1)
dataset2 <- data.frame(V1 = rpois(100000, 1.602))