Multiple individual plots at a time

Using ggplot2:

qplot(carat, price, data = diamonds) + facet_grid(cut ~ color ~ clarity)

Not quite what I was hoping for. How could something like this be done, except for creating separate graph grids to a level of clarity, for example.

qplot(carat, price, data = diamonds[diamonds$clarity=="SI2", ]) + facet_grid(cut ~ color)
qplot(carat, price, data = diamonds[diamonds$clarity=="VS1", ]) + facet_grid(cut ~ color)

etc.

Something using casting would be perfect.

0
source share
2 answers

Here is what I will do:

base = qplot(carat, price, data = diamonds) + facet_grid(cut ~ color)
lp = dlply(diamonds, "clarity", `%+%`, e1 = base)

library(gridExtra)
do.call(grid.arrange, lp) # all in one page

# or multiple pages (with layout passed to grid.arrange)
all = do.call(marrangeGrob, c(lp, ncol=2, nrow=1))
ggsave("multipage.pdf", all, width=12) 
+1
source

For three faceted variables, try facet_wrap.

facet_wrap(~ cut + color + clarity)

I re-read the question. If you really need a few graphs (it wasn’t so clear from the phrase), then just go through the levels clarity.

for(clarity in levels(diamonds$clarity))
{
  p <- qplot(carat, price, data = diamonds[diamonds$clarity == clarity, ]) + 
    facet_grid(cut ~ color)
  print(p)
}

Or if you are for-loop-phobic,

l_ply(
  levels(diamonds$clarity),
  function(clarity)
  {
    qplot(carat, price, data = diamonds[diamonds$clarity == clarity, ]) + 
      facet_grid(cut ~ color)
  }
)

If you are typing on the screen, first enable history recording. Otherwise, enable the call ggsavein your loop.

+2

All Articles