简体   繁体   English

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

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

I have two probability distribution curves, a Gamma and a standarized Normal, that I need to compare: 我需要比较两条概率分布曲线,即伽马曲线和标准正态分布:

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)

The output is like this 输出是这样的

两条分布曲线

However I need to have the two curves separated by means of the faceting mechanism provided by ggplot2, sharing the Y axis, in a way like shown below: 但是,我需要通过ggplot2提供的分面机制将两条曲线分开,并共享Y轴,如下所示:

多面的

I know how to do the faceting if the depicted graphics come from data (ie, from a data.frame), but I don't understand how to do it in a case like this, when the graphics are generated on line by functions. 如果所描绘的图形来自数据(例如,来自data.frame),我知道如何进行刻面处理,但是当图形是通过函数在线生成时,我不知道在这种情况下该如何做。 Do you have any idea on this? 您对此有什么想法吗?

you can generate the data similar to what stat_function is doing ahead of time, something like: 您可以提前生成类似于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)

The issue with doing facet_wrap is that the same stat_function is designed to be applied to each panel of the faceted variable which you don't have. 执行facet_wrap的问题是,将相同的stat_function设计为应用于没有多面变量的每个面板。

I would instead plot them separately and use grid.arrange to combine them. 相反,我会分别绘制它们并使用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)

Otherwise create the data frame with y values from both pgammaX and pnorm and categorize them under a faceting variable. 否则,使用pgammaX和pnorm的y值创建数据框,并将其归类为构面变量。

Finally I got the answer. 终于我得到了答案。 First, I need to have two data sets and attach each function to each data set, as follows: 首先,我需要有两个数据集,并将每个函数附加到每个数据集,如下所示:

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)

Then, using facet_wrap(), I separate into two graphics according to the category assigned to each data set, and establishing a free_x scale. 然后,使用facet_wrap(),根据分配给每个数据集的类别将其分成两个图形,并建立一个free_x比例尺。

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

The result is shown below: 结果如下所示:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM