-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathFigures_for_loop.Rmd
More file actions
57 lines (47 loc) · 1.23 KB
/
Figures_for_loop.Rmd
File metadata and controls
57 lines (47 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
---
title: "Figures in for loop"
author: "EE Holmes"
output:
pdf_document: default
html_document: default
---
With base R plots, you can just put them in a for loop.
```{r}
library(ggplot2)
for( i in 1:2 ) {
df <- data.frame(t=1:100, y=rnorm(100))
plot(df$t, df$y)
cat('\n\n')
}
```
With **ggplot2** you need to assign to an object and print that.
```{r}
library(ggplot2)
for( i in 1:2 ) {
df <- data.frame(t=1:100, y=rnorm(100))
p <- ggplot(df, aes(t, y)) + geom_point()
print(p)
cat('\n\n')
}
```
To have figure captions that change, you need to create all your figure captions and give that to `fig.cap` as a vector.
```{r fig.cap = paste("Figure", 1:2)}
library(ggplot2)
for( i in 1:2 ) {
df <- data.frame(t=1:100, y=rnorm(100))
p <- ggplot(df, aes(t, y)) + geom_point()
print(p)
cat('\n\n')
}
```
You can have figures appear side by side, though using figure captions will break this. You can `cat()` out a legend but you'll need to set `results='asis'`.
```{r echo=FALSE, fig.hold=TRUE, out.width="50%", results='asis'}
library(ggplot2)
for( i in 1:2 ) {
df <- data.frame(t=1:100, y=rnorm(100))
plot(df$t, df$y)
p <- ggplot(df, aes(t, y)) + geom_point()
print(p)
cat(paste("Figure", i, "\n\n"))
}
```