2

I have a sequence of normally distributed posterior densities from Bayesian updating beliefs about a parameter in a model. Suppose the sequences of means and standard deviations of the posteriors are,

mean <- c(5,4,3,2,1)
sd <- c(7,6,5,4,3)

Where the distribution N(5,7) is the first posterior, N(4,6) is the second posterior and so on. I wanted to plot them as a sequence of densities so the axes are rotated (support of the distribution goes from the bottom to the top) and such that the densities are all in order from left to right. I understand how to plot the densities using stat_function, and how to put plots in facets with facet_grid, but I'm struggling to combine it all together.

Ivan
  • 33
  • 3

1 Answers1

3

Is this what you had in mind:

library(reshape2)
library(ggplot2)

m <- c(5,4,3,2,1)
s <- c(7,6,5,4,3)
x=seq(-20,30,0.1)

# Create a data frame of density values
dat = data.frame(x, mapply(function(m,s) {dnorm(x, m, s)}, m, s))
names(dat) = c("x", paste0("Mean=",m," SD=",s))

ggplot(melt(dat, id.var="x"), aes(x, value)) +
  geom_line() + 
  coord_flip() + 
  facet_grid(. ~ variable) +
  theme_bw()

enter image description here

Or with a color aesthetic instead of faceting:

ggplot(melt(dat, id.var="x"), aes(x, value, color=variable)) +
  geom_line() + labs(color="") + 
  coord_flip() + 
  theme_bw()

enter image description here

Initially, I was trying to do it without creating a separate data frame. Here's a way to do that, but I wasn't quite sure how to map to, say, a color aesthetic or to facet using this method (and this SO answer from @hadley suggests it's not possible (though that was six years ago and perhaps the situation is different now)):

ggplot(data.frame(x), aes(x)) + 
  mapply(function(m, s) {
    stat_function(fun = dnorm, args = list(mean = m, sd = s))
  }, m = m, s = s) + 
  coord_flip()
Community
  • 1
  • 1
eipi10
  • 91,525
  • 24
  • 209
  • 285