Arya McCarthy
Arya McCarthy

Reputation: 8829

Stack multiple plots vertically in R or Python

I am trying to reproduce the plot below, which shows the mean and standard deviation in separate sections of the y-axis. Rather than plotting them in separate subfigures, they share the x-axis.

this plot

I see this suggestion to use the lattice library in R, but I'd like to do it with labels to the side, instead of separating each graph—as in the example I've provided.

Upvotes: 0

Views: 703

Answers (1)

eipi10
eipi10

Reputation: 93861

In R, here's a ggplot2 version:

library(ggplot2)
library(reshape2)

# Fake data
set.seed(2)
n = 20
dat = data.frame(mp=rep(seq(0,1,length=n),2),
                 group=rep(LETTERS[1:2], each=n),
                 Mean=rep(c(1,1.1),each=n)*seq(0.7,0,length=n),
                 SD=rep(c(0.1,.12), each=n) + rnorm(2*n,0,0.02))

dat = melt(dat, id.var=c("mp","group"))
dat$variable = factor(dat$variable, levels=c("SD","Mean"))

ggplot(dat, aes(mp, value, colour=group)) +
  facet_grid(variable ~ ., scales="free", space="free", switch="y", ) +
  geom_vline(xintercept=0.6, colour="grey40", linetype="11") +
  geom_line() +
  geom_point() +
  scale_y_continuous(breaks=function(x) {round(seq(0,max(x),length=5)[-5],1)}) +
  expand_limits(y=c(0,0.2)) +
  labs(x="Mixing Parameter", y="") +
  theme_bw() +
  theme(panel.spacing.y=unit(0,"lines"),
        strip.placement="outside",
        strip.background=element_rect(fill=NA, colour=NA)) +
  guides(colour=FALSE)

enter image description here

Upvotes: 2

Related Questions