1

I wanted to make a graph using facet_wrap and plot it in different pages in a pdf file. I've read son many options, and this works: R + ggplot: plotting over multiple pages but only when you have the same rows in each page.

I have this demo data to try explain my case:

A <- data.frame(TIME = rep(c(0, 5, 10, 15, 30, 45, 60), 5))
A$C <- (1 - exp(-0.2*A$TIME))
A$ID <- rep(1:5, each = 7)
A$R <- rnorm(35, mean = 1, sd = 0.01)
A$C2 <- A$C*A$R
Pages <- 5
A2 <- A[c(1,4:8,10:22,24:35),]

So, I have ID with different number of observations. I tried to make a vector with the number of observation in each ID (I want an ID per page), but it doesn't work.

nrws <- ddply(A2, .(ID), "nrow")
nsamp <- nrws[,2]

pdf("Test.pdf")
for (i in seq(Pages))
  {
    slice = seq(((i-1)*nsamp[i]),(i*nsamp[i]))
    slice2 = slice[!(slice > nrow(A2))]
    A3 = A2[slice2,]
    p1 <- ggplot(A3, aes(x = TIME, y = C2)) +  
      geom_line(size = 0.5) +
      geom_point(size = 1) +
      facet_wrap(~ID)
print(p1)
  }
dev.off()

Could you help me?

Thanks in advances, Nacho

Community
  • 1
  • 1
Nacho Glez
  • 385
  • 3
  • 15

1 Answers1

1

I think you were overthinking trying to calculate your "slices". Maybe you want this?

Not entirely sure. If you only want one ID per page you don't need facet_wrap, and you will probably need to set the scale explicitly to keep it the same from page to page.

library(plyr)

A <- data.frame(TIME = rep(c(0, 5, 10, 15, 30, 45, 60), 5))
A$C <- (1 - exp(-0.2*A$TIME))
A$ID <- rep(1:5, each = 7)
A$R <- rnorm(35, mean = 1, sd = 0.01)
A$C2 <- A$C*A$R
Pages <- 5
A2 <- A[c(1,4:8,10:22,24:35),]

nrws <- ddply(A2, .(ID), "nrow")
nsamp <- nrws[,2]

pdf("Test.pdf")
for (i in seq(Pages))
{
#  slice = seq(((i-1)*nsamp[i]),(i*nsamp[i]))
#  slice2 = slice[!(slice > nrow(A2))]
#  A3 = A2[slice2,]

  A3 = A2[A2$ID==i,]
  p1 <- ggplot(A3, aes(x = TIME, y = C2)) +  
    geom_line(size = 0.5) +
    geom_point(size = 1) +
    facet_wrap(~ID)
  print(p1)
}
dev.off()
Mike Wise
  • 22,131
  • 8
  • 81
  • 104
  • You are right, with your solution (easy than mine) I don't need facet_wrap. Thanks a lot!! – Nacho Glez Nov 06 '15 at 12:56
  • You will probably need to use `scale_y_continuous` to set the y-range explicitly, otherwise it will vary from page to page and they will be harder to compare. That is something that `facet_wrap` does for you automatically, but only in a given `ggplot` call. – Mike Wise Nov 06 '15 at 12:59