I'm working on a rather long code using R markdown, divided into chunks. Plot appear under the appropriate chunk. I'd like to keep this behaviour, but additionally I want to save them to a specified folder. I've tried different methods listed here How to save a plot as image on the disk? (and elsewhere on the Internet), but nothing seems to work.
My reproducible example:
png('cars_plot.png')
plot(cars)
dev.off()
This code saves the plot, but doesn't show it (it only returns "null device 1"). I've also tried dev.print and dev.copy, with the same result.
Thank you in advance!
Clarification: I run my chunks one by one, I don't want to convert my results to pdf/html yet. So knitr: include figures in report *and* output figures to separate files or change where rmarkdown saves images generated by r code don't answer my question.
You can always graph it twice in the same markdown chunk, like this:
plot(cars)
png('cars_plot.png')
plot(cars)
dev.off()
Related
I'm having a problem with assigning LaTeX environments within an RMarkdown for-loop code-chunk.
In short, I've written an R Markdown document and a series of R-scripts to automatically generate PDF reports at the end of a long data analysis pipeline. The main section of the report can have a variable number of sections that I'm generating using a for-loop, with each section containing a \subsection heading, a datatable and plot generated by ggplot. Some of these sections will be very long (spanning several pages) and some will be very short (~1/4 of a page).
At the moment I'm just inserting a \pagebreak at the end of each for-loop iteration, but that leaves a lot of wasted space with the shorter sections, so I'm trying to "group" each section (i.e. the heading, table and chart) so that there can be several per page, but they will break to a new page if the whole section won't fit.
I've tried using a figure or minipage environment, but for some reason those commands are printed as literal text when the plot is included; these work as expected with the heading and data table, but aren't returned properly in the presence of the image.
I've also tried to create a LaTeX samepage environment around the whole subsection (although not sure this will behave correctly with multi-page sections?) and then it appears that the Markdown generated for the plot is not interpreted correctly somewhere along the way (Pandoc?) when it's within that environment and throws an error when compiling the TeX due to the raw Markdown ![]... image tag.
Finally, I've also tried implementing \pagebreak[x] and \nopagebreak[y] hints at various points in the subsection but can't seem get these to be produce the desired page breaking behaviour.
I've generated an MWE that reproduces my issues below.
I'd be really grateful for any suggestions on how to get around this, or better ways of approaching "grouping" of elements that are generated in a dynamic fashion like this?
---
title: "Untitled"
author: "I don't know what I'm doing"
date: "26/07/2020"
output:
pdf_document:
latex_engine: xelatex
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, dev = "cairo_pdf")
```
```{r cars, results='asis'}
for (i in 1:5){
cat("\\begin{figure}")
cat(paste0("\\subsection{This is subsection ",i,"}"))
cat("\\Huge Here's some bulk text that would represent a data table... kasvfkwsvg fiauwe grfiwgiu iudaldbau iausbd ouasbou asdbva asdbaisd i iuahihai hiuh iaiuhqijdblab ihlibljkb liuglugu h uhi uhi uhqw iuh qoijhoijoijoi qwegru wqe grouw egq\\newline")
plot(mtcars$wt,mtcars[,i])
cat("\\end{figure}")
}
```
Edit to add: interestingly these figure and minipage environments seems to work as expected when executing the same example in an .Rnw using knitr... so does that narrow it down to an issue with Pandoc? Again, any help much appreciated!
What happens is that the raw TeX commands are not treated as TeX when going through Markdown. You can fix that by explicitly marking the relevant snippets as LaTeX:
for (i in 1:5){
cat("`\\begin{figure}`{=latex}")
cat(paste0("\\subsection{This is subsection ",i,"}"))
cat("\\Huge Here's some bulk text that would represent a data table... kasvfkwsvg fiauwe grfiwgiu iudaldbau iausbd ouasbou asdbva asdbaisd i iuahihai hiuh iaiuhqijdblab ihlibljkb liuglugu h uhi uhi uhqw iuh qoijhoijoijoi qwegru wqe grouw egq\\newline")
plot(mtcars$wt,mtcars[,i])
cat("`\\end{figure}`{=latex}")
}
See the generic raw attribute section in the pandoc manual for details.
I have a .Rpres file in RStudio. I would like to include code, but not have it run (I am only showing the code to explain how it works). Is it possible to accomplish this (and ensure that it will not produce errors, because it is not running)?
Have you tried eval=FALSE in the knitr code chunk options? e.g.:
```{r eval=FALSE}
print("Don't run me")
```
{r, eval=F, echo=T} will include the R source code in the output file while it is not evaluated
Posting for anyone who may come across this like I have. I've found that for small examples (if you don't want to use chunks), you can also just use back ticks like you would with regular markdown inline, but just don't add the "r" at the beginning:
`plot(cars)`
Will print the code itself, but will not print the plot.
I am using knit()and markdownToHTML() to automatically generate reports.
The issue is that I am not outputting plots when using these commands. However, when I use RStudio's Knit HTML button, the plots get generated. When I then use my own knit/markdown function, it suddenly outputs the plot. When I switch to another document and knit that one, the old plot appears.
Example:
```{r figA, result='asis', echo=TRUE, dpi=300, out.width="600px",
fig=TRUE, fig.align='center', fig.path="figure/"}
plot(1:10)
```
Using commands:
knit(rmd, md, quiet=TRUE)
markdownToHTML(md, html, stylesheet=style)
So I guess there are 2 questions, depending on how you want to approach it:
What magic is going on in Rstudio's Knit HTML?
How can I produce/include without depending on RStudio's Knit HTML button?
The only issue I see here is that this doesn't work when you have the chunk options {...} spanning two lines. If it's all on one line, it works fine. Am I missing something?
See how this is not allowed under knitr in the documentation:
Chunk options must be written in one line; no line breaks are allowed inside chunk options;
RStudio must handle linebreaks in a non-standard way.
This is really embarrassing, I really thought I read the documentation carefully:
include: (TRUE; logical) whether to include the chunk output in the
final output document; if include=FALSE, nothing will be written into
the output document, but the code is still evaluated and plot files
are generated if there are any plots in the chunk, so you can manually
insert figures; note this is the only chunk option that is not cached,
i.e., changing it will not invalidate the cache
Simply adding {..., include=TRUE} did the trick. I would say it would be a pretty sensible default though.
I am having problems with long outputs in the new Rstudio presentation format. The latter looks much more efficient than Latex+ Sweave but I miss an option that automatically adds page breaks so that the output spans multiple pages, e.g. the "allowframebreaks" for beamer slides.
I also tried knitter chunk-options but could not find a solution.
Here is a minimal Rpres file in which only a part of the output is shown.
example
========================================================
```{r}
rnorm(100)
```
Any help much appreciated.
I'm creating a larger number of plots in R and save them as PDF (using grDevices / pdf). Is there an easy way to add a (meta-data) table of contents to the PDF as it is created?
I don't mean to add a separate page, but a TOC that PDF viewers like Preview.app display in the sidebar to make navigation easier.)
Example of such a TOC:
The only way I know is with LaTeX, but you don't necessarily need Sweave; perhaps you could just generate the LaTeX file directly with your RPython code. If you've got two pictures which are 6x6 (the default size) named tmp-001.pdf and tmp-002.pdf, this is how you'd make a section called Section A with two subsections for the two pictures.
\documentclass{article}
\usepackage[paperwidth=6in, paperheight=6in, margin=0in]{geometry}
\usepackage{hyperref}
\usepackage{graphicx}
\parindent 0pt
\begin{document}
\pdfbookmark[1]{Section A}{anchorname_aa}
\pdfbookmark[2]{plot aa}{anchorname_aa}
\includegraphics{tmp-001.pdf}
\newpage
\pdfbookmark[2]{plot bb}{anchorname_bb}
\includegraphics{tmp-002.pdf}
\end{document}
You could create a first page using the names of your objects or plots as the arguments to text in columns.
plot(1:10,1:10, type="n", main ="Index", axes=FALSE,frame.plot=FALSE,xlab="")
text(1,10, "plot")
text(3,10, "page")
text(5,1:10, rev(1:10+1))
text(2,1:10, rev(letters[1:10]))
I cannot think of a way to generate a navigable TOC, but this option may be more pleasing and easier to integrate with Beamer-type displays. The Hmisc package function latex provides an interface to the Latex longtable package. My Latex-fu is weak but if yours is stronger, you could also divert the dvi code that is created for integration within other applications. I get an intermediate dvi file put in a temporary directory which then opens my dvi viewer and allows saving as pdf:
require(Hmisc)
?latex # you will probably want to review this
latex(Plot_list<-data.frame(Plots=letters[1:10], Pages=2:11))
Not as far as I know. I think you have to use sweave for that.