Manne
Manne

Reputation: 3

Plot the PDF of gamma, normal and t in ggplot combined

I would like to plot the pdf of the distributions normal, gamma and t. I just want to generate a random sample with each distributions. The purpose is just to illustrate the differences between the graphs. I am not sure if it is possible to get them combined. I know how to plot the curves separately with this code:

ggplot(data = data.frame(x = c(-3, 3)), aes(x)) +
  stat_function(fun = dnorm, n = 101, args = list(mean = 0, sd = 1)) + ylab("") +
  scale_y_continuous(breaks = NULL)
ggplot(data = data.frame(x = c(-10, 10)), aes(x)) +
  stat_function(fun = dt, n = 1000, args = list(df = 3)) + ylab("") +
  scale_y_continuous(breaks = NULL)

ggplot(data = data.frame(x = c(-10, 10)), aes(x)) +
  stat_function(fun = dgamma, n = 1000, args = list(shape = 3)) + ylab("") +
  scale_y_continuous(breaks = NULL)

I would like to combine all these into one plot, for example one colour for each graph. Is this possible in ggplot? Appreciate if someone have any input.

Edit: I know that with the gridextra package and the function grid.arrange I can combine them into picture. But I want to have them in the same graph. Also I do not really understand why the t distribution is so similar to the normal distribution. I have tried with n = 5 and they are still very similar. I would like to illustrate difference between them. Regards

Upvotes: 0

Views: 479

Answers (2)

Elk
Elk

Reputation: 532

You don't need to specify data in the ggplot call...you can add it to each stat_function call instead.

ggplot() +
  stat_function(data = data.frame(x = c(-3, 3)), aes(x), fun = dnorm, n = 101, args = list(mean = 0, sd = 1), colour = "red") +
  stat_function(data = data.frame(x = c(-10, 10)), aes(x), fun = dt, n = 1000, args = list(df = 3), colour = "blue") +
  stat_function(data = data.frame(x = c(-10, 10)), aes(x), fun = dgamma, n = 1000, args = list(shape = 3), colour = "green") + 
  ylab("") +
  scale_y_continuous(breaks = NULL)

Graph

Upvotes: 1

Ben Bolker
Ben Bolker

Reputation: 226087

It would be easier (IMO) to construct the data frame yourself and then pass it to ggplot.

library(tidyverse)
xvec <- seq(-10,10,length=101)
dd <- purrr::map_dfr(list(normal=dnorm(xvec, 0, 1),
                          t=dt(xvec,df=3),
                          gamma=dgamma(xvec,shape=3)),
     ~ tibble(x=xvec, y=.),
    .id="distribution")
ggplot(dd, aes(x, y, colour=distribution)) + geom_line()

normal, t(3), gamma curves

Curves look a tiny bit non-smooth at the peak, might be worth increasing length to 501 when defining xvec ...

Upvotes: 0

Related Questions