3
$\begingroup$

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 enter image description here 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: enter image description here

I know how to do the faceting if the depicted graphics come from data (i.e., 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. Do you have any idea on this?

$\endgroup$
1

1 Answer 1

1
$\begingroup$

I would separate the creation of the data from the plotting operation, if I were you. ggplot2::facet_wrap allows you to plot each of the cumulative distributions in each own panel. Here is how I would do it.

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

Gamma <- pgammaX(seq(from=4, to = 8, by = 0.1))
Normal <- pnorm(seq(from=-4, to = 3.9, by = 0.1))

data <- data_frame(
  x = seq(-4,8,by=0.1),
  y = c(Normal, Gamma),
  # use factor to make the plot for Normal to appear first
  distribution = factor(c(rep(c("Normal", "Gamma"), 
                          times = c(length(Normal), length(Gamma)))),
                          levels = c("Normal", "Gamma"))
)

library(dplyr)    
library(ggplot2)

data %>%  ggplot(aes(x, y)) + 
  geom_line() + 
  # use facet_wrap to plot each cummulative distribution in each own panel      
  facet_wrap(~distribution, scales = "free_x")

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.