简体   繁体   中英

plot one in three plots on knitr

I want to run through a script and make many plots, but only in the end plot then out to markdown
So what I tried to do is save many plots as a list of plots, but not publish them to markdown.
Second step is go throgh the list and plot one in three plots but for some reason i get only the last plot.

#+ setup, include=FALSE

library(knitr)
opts_chunk$set(fig.path = 'figure/silk-', fig.width = 10, fig.height = 10)

#' Make a list of plots.
#' 
#/* do not show in Markdown
index = 1
plots<-list()
for (let in letters)
{
 plot(c(index:100))
 assign(let,recordPlot())
 plot.new()
 plots[index]<-(let)
 index=index+1
}
#*/go through list of plots and plot then to markdown file
for (p in seq(from = 1, to = length(plots), by =3))
{

    print(get(plots[[p]]))

} 

There are a few errors in your code as relics from other programming languages:

  • Don't use assign at all. People who are allowed to use assign will not use it.
  • plot.new() creates an empty page. Leave out
  • Do not use get . It had its uses in S-Plus, but is not helpful nowadays.
  • with lists, use [[ , eg plots[[index]]
  • Most important: What you want makes sense, but standard graphics (eg plot) is badly suited for this because it was build with action in mind, not with assignment. Both lattice and ggplot2 graphics are assignment-aware.
  • In the example, I use lapply as a demonstration of standard R practices. A for-loop will not be slower in this case, because plotting takes most of the time.
  • Better use facets or panels for this, instead of many individual plots.

`

library(knitr)
library(lattice)
# Make a list of plots.
# do not show in Markdown
plots = lapply(letters[1:3],
    function(letter) {xyplot(rnorm(100)~rnorm(100), main=letter)})

# print can use a list (not useful in this case)    
print(plots)

# go through list of plots and plot then to markdown file
# This only makes sense if you do some paging in between. 
for (p in seq(from = 1, to = length(plots), by =3))
{
  print(plots[[p]])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM