Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot several pictures with different size in a "for" loop

I am new to knitr and markdown and this is my first question asked. Maybe this question has a simple answer that I just can't find.

I have a for-loop, which creates 3 ggplots. The loop runs 300 to 400 times depending on the data input. I want to define the size of these 3 pictures as:

1st picture: width = 7, height = 3

2nd picture: width = 7, height = 3

3nd picture: width = 7, height = 12

So far I am using the following code:

```{r calc, echo=FALSE, warning=FALSE, message=FALSE, results='asis', fig.show='asis',fig.height=3}
for(x.PS in 1:length(trace.input)) 
{
# some data transformation by self-written functions

# create and save plot for the normalised version
ggp.PS.norm <- ggplot(print.PS.norm, aes(x = Time, y = Voltage, col = Pulse))
fig.PS.norm <- ggp.PS.norm + geom_line()

# create and save plot for the modified version
ggp.PS.smooth <- ggplot(print.PS.smooth, aes(x = Time, y = Voltage, col = Pulse))
fig.PS.smooth <- ggp.PS.smooth + geom_line()

# create and save plot for the modified version as facet grid
fig.PS.smooth.single <- ggp.PS.smooth + geom_line() + facet_grid(FigCol ~ FigRow)

print(fig.PS.norm)
print(fig.PS.smooth)
print(fig.PS.smooth.single)
}
```

In the end I hope to get one big PDF-file with 3 x 300 to 400 pictures

I hope this code is understandable even without any hard data.

best paj

like image 374
alias_paj Avatar asked Oct 25 '25 22:10

alias_paj


1 Answers

I don't know if this is kosher but here is one approach:

adapted from here

I'm using rmarkdown since that is what your question is in, but this could be adapted to latex

---
output: 
  html_document:
    css: ~/knitr.css
---

```{r, include=FALSE}
library(knitr)
opts_knit$set(progress = FALSE, verbose = FALSE)
opts_chunk$set(warning=FALSE, message=FALSE, echo=FALSE)

## this function is basically creating chunks within chunks, and then
## I use results='asis' so that the html image code is rendered 
kexpand <- function(ht, cap) {
  cat(knit(text = knit_expand(text = 
     sprintf("```{r %s, fig.height=%s, fig.cap='%s'}\n.pl\n```", cap, ht, cap)
)))}

library(ggplot2)
```


```{r, results='asis', fig.width=7}
for (ii in 1:2) {
  ## do some stuff

  cat('<br />')
  cat(paste0('Page', ii))

  ## all plots should be saved as .p1 and then use kexpand
  .pl <- qplot(mpg, wt, data=mtcars)
  kexpand(3, 'fig1')

  .pl <- qplot(mpg, wt, data=mtcars, colour=cyl)
  kexpand(3, 'fig2')

  .pl <- qplot(mpg, wt, data=mtcars, size=cyl)
  kexpand(7, 'fig3')

  cat('<br /><br />')
}
```

And this is my output

enter image description here enter image description here enter image description here

like image 55
rawr Avatar answered Oct 27 '25 15:10

rawr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!