如何在 R / ggplot2 中以多面方式绘制两条分布曲线?

How to plot two distribution curves in a faceted way in R / ggplot2?

我有两条概率分布曲线,一条 Gamma 曲线和一条标准化的正态曲线,我需要比较它们:

library(ggplot2)

pgammaX <- function(x) pgamma(x, shape = 64.57849, scale = 0.08854802)

f <- ggplot(data.frame(x=c(-4, 9)), aes(x)) + stat_function(fun=pgammaX)
f + stat_function(fun = pnorm)

输出是这样的

但是我需要通过 ggplot2 提供的刻面机制将两条曲线分开,共享 Y 轴,如下所示:

如果描绘的图形来自数据(即来自 data.frame),我知道如何做分面,但我不明白在这种情况下如何做,当图形由函数在线生成。你有什么想法吗?

您可以生成类似于 stat_function 提前执行的数据,例如:

x <- seq(-4,9,0.1)
dat <- data.frame(p = c(pnorm(x), pgammaX(x)), g = rep(c(0,1), each = 131), x = rep(x, 2) )
ggplot(dat)+geom_line(aes(x,p, group = g)) + facet_grid(~g)

执行 facet_wrap 的问题是相同的 stat_function 旨在应用于您没有的分面变量的每个面板。

我会单独绘制它们并使用 grid.arrange 组合它们。

f1 <- ggplot(data.frame(x=c(-4, 9)), aes(x)) + stat_function(fun = pgammaX) + ggtitle("Gamma") + theme(plot.title = element_text(hjust = 0.5))
f2 <- ggplot(data.frame(x=c(-4, 9)), aes(x)) + stat_function(fun = pnorm) + ggtitle("Norm") + theme(plot.title = element_text(hjust = 0.5))
library(gridExtra)
grid.arrange(f1, f2, ncol=2)

否则,使用 pgammaX 和 pnorm 的 y 值创建数据框,并将它们分类在分面变量下。

终于找到答案了。首先,我需要有两个数据集,并将每个函数附加到每个数据集,如下:

library(ggplot2)

pgammaX <- function(x) pgamma(x, shape = 64.57849, scale = 0.08854802)

a <- data.frame(x=c(3,9), category="Gamma")
b <- data.frame(x=c(-4,4), category="Normal")

f <- ggplot(a, aes(x)) + stat_function(fun=pgammaX) + stat_function(data = b, mapping = aes(x), fun = pnorm)

然后,使用facet_wrap(),我根据分配给每个数据集的类别分成两个图形,并建立free_x比例。

f + facet_wrap("category", scales = "free_x")

结果如下图: