0

I'm using the below code to generate a series of plots. Unfortunately, when you knit this RMD file, the line numbers appear before each chart.

---
title: "Test"
author: "John"
date: "September 10, 2015"
output: pdf_document
---


```{r, echo=FALSE, warning=FALSE, message=FALSE}
library(dplyr)
library(ggplot2)

makePlots <- function(groupedTable, grouping){
  ggplot(groupedTable) +
  geom_bar(aes(disp), binwidth = 20) +
  ggtitle(grouping)
}

allPlots <- mtcars %>% group_by(cyl) %>% do(plots = makePlots(.,unique(.$cyl)))

allPlots$plots
```

Produces this output:

Output

In the screencap, you will see
## [[1]]
and
##
## [[2]]

I would like to just have the graphs without those. Any ideas?

John Tarr
  • 717
  • 1
  • 9
  • 21

1 Answers1

3

You can print them in a for loop instead of printing the list:

for (p in allPlots$plots) {
    print(p)
}

An alternative is to combine the plots into one with grid.arrange, as shown here. This also allows you to choose how many rows and/or columns the graphs are organized into.

library(gridExtra)

args <- c(allPlots$plots, ncol = 1)
do.call(grid.arrange, args)
Community
  • 1
  • 1
David Robinson
  • 77,383
  • 16
  • 167
  • 187
  • The for loop does not work. It actually creates more text. – John Tarr Sep 10 '15 at 17:49
  • @JohnTarr Typo on my part: I wrote `for p in allPlots` rather than `for p in allPlots$plots`. Try this code now. – David Robinson Sep 10 '15 at 17:50
  • Thank you, that for loop worked. What package is grid.arrange from? gridExtra? – John Tarr Sep 10 '15 at 17:52
  • @JohnTarr Sorry I forgot to include that: `library(gridExtra)` – David Robinson Sep 10 '15 at 17:52
  • Sorry to be a pain, but is there any way to tell gridExtra to make each row its own page? the for loop should work for that if not, but it would be nice to have some more control over the layout, perhaps putting two side by side per page. Currently, it smashes them all into one page. – John Tarr Sep 10 '15 at 17:58
  • @JohnTarr You can't have `grid.arrange` do that, but you could do a for loop of `grid.arrange` calls. (It ends up being a small bit of hassle to handle cases where there's an odd number- you need to check that on the last loop you only plot one graph). What might work better is a for loop, but set your `fig.width` and `fig.height` options so that the figures are plotted side by side – David Robinson Sep 10 '15 at 18:05