Low quality figures using RMD to create latex docs - r

Good morning,
I have decided to try RMarkdown to create short white papers that I will be updating regularly. The rmd code extracts Fed data, organizes it, and then creates graphs that are placed alongside some short commentary about them.
My question is about the output. The figures created within Rstudio are crisp and what I wanted; the pdf output should the lines as thicker and much less crisp.
My code chunk is below. I've tried changing the dpi at the top of the chunk, but that has not changed the pdf output.
Any ideas about getting the same crisp lines within RStudio onto pdf using Rmarkdown?
Thanks!
```{r echo=FALSE,dpi=600,message=FALSE}
# Create caption
mycaption<- "Source: FredII - Federal Reserve Bank of St. Louis"
# Wrap caption 120 characters:
mycaption <- paste0(strwrap(mycaption, 120), sep="", collapse="\n")
# Create Plot
ggplot(data=dt2,aes(x=date,y=value,color=name,linetype=name))+
geom_line(size=0.7)+
labs(x="",y="Interest Rates",
title="Comparing Interest Rates by Source/Maturity",
caption=mycaption ) +
guides(title="New Legend Title")
```

An easy solution to have higher quality plotting output when compiling to PDF is to use the tikz graphics device by setting the chunkk option dev="tikz" (or globally using opts_chunk$set(dev = "tikz")).
Tikz is a TeX package that allows to create vector graphics using an easy syntax. Using vector graphics has the advantage that they are scalable, annotations in your plot will use the same main font that is used in the document and you can easily add math symbols to your plot using the TeX syntax:
plot(..., main = "$\\bar{\\mu}$")

Related

Saving AND showing plots in rmd file

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()

Control alignment of two side-by-side plots in knitr

I cannot figure out how to arrange two side-by-side plots as explained in the knitr graphics manual page 2 (http://yihui.name/knitr/demo/graphics/). I use the following MWE and the output is below. I would like them to be aligned as shown in the manual for the two cars plots (also on page 2 of the manual). The pdf is generated in RStudio (Knit to PDF).
---
title: "Untitled"
output: pdf_document
---
## R Markdown
```{r,echo=FALSE,out.width='.49\\linewidth', fig.width=3, fig.height=3}
barplot(1:4)
barplot(4:7)
```
To center two plots you can add fig.align='center'to your chunk options. If it produces one plot above the other add also fig.show='hold'. The result should be two centered graphs.
So your final chunk option should look something like:
{r,echo=FALSE, out.width='.49\\linewidth', fig.width=3, fig.height=3,fig.show='hold',fig.align='center'}
An alternative which worked for me: save the plots as files, then put the picture markdown on the same line (from here).
## Show images
![](file1.pdf) ![](file2.pdf)
You can save ggplot plot objects with ggsave.
Base plots are a bit more complicated, see for example here.
I'm putting this answer here because it helped me. Whether it's better for you or not depends on your situation.

Control size of points in figure produced by knitr

I've used knitr to produce a PDF. This is a screenshot from 1 page of the PDF:
After a couple of hours of fiddling various knitr options (fig.width, fig.height, out.height, out.width), the page of the PDF looks half decent. But...the axis text, the annotations and the points in the plot are still too small relative to the text in the PDF.
Is there is a way to have knitr automatically size the text/points in the plot so fit well inside the PDF?
EDIT: with the suggested fig.width="3.7" and out.width = "\\columnwidth"

How do I add a note or text in addition to the caption to a knitr figure for latex output?

I am using knitr to write my thesis and compiling it as a latex document. I have successfully included figures with the appropriately labeled caption; however, in addition to the caption I would like to include additional lines of text directly below the caption and associated with the figure. For example, below the caption I would like to hove: "NOTE: These data are distributed with mu=0 and sd=1" and "SOURCE: These data were randomly generated in R."
EDIT 1 to question: I also need to have a list of figures page with just the caption information included not any of the NOTE or SOURCE information. In addition the caption under the figure must be centered, while the NOTE and SOURCE are left hand justified.
I believe that many publications have figures with notes about the figure or information about the source of the data that is separate from the caption title; so, I believe this question is not just applicable to me.
EDIT 1 to code. Here is a synthesis of the code that #user29020 provided and the link they suggested, as well as the .pdf work around I have assembled from other posts. The advantage of the "pure" knitr method provided by #user29020 is that the plot is beautiful with the text scaled consistently with the body of the text. The disadvantage is a lack of control of the caption information: I would like to center the "Caption" element and left justify the and sub-caption lines and I do not know how to accomplish this; so, if anybody knows how to do this that would be great. The advantage of the pdf work around is that I have greater control over the captions. In addition to not taking full advantage of knitr's ability to create and track figures, the disadvantage is that while the font matches, by using "Ghostscript" the scaling appears a little off and needs to be adjusted in an ad-hoc fashion in the R code.
\documentclass{article}
\usepackage{caption}
\usepackage{tikz}%Draw Graphs
\begin{document}
\listoffigures
\newpage
%THIS IS A SYNTHESIS OF user29020 CODE AND THE LINK THEY PROVIDED IN THEIR COMMENTS
<<cap-setup1,include=FALSE>>=
scap="This is a Caption."
NOTE="NOTE: Here is a note with one linebreak from above."
SOURCE="SOURCE: Here is my source with an extra linebreak to separate it."
EXTRA="{\\tiny EXTRA: Here is smaller text. You could explore more text sizing in \\LaTeX.} And bigger again."
hspace="\\\\\\hspace{\\textwidth}"
cap<- paste(
scap,
hspace,
NOTE,
hspace,
SOURCE,
hspace,
EXTRA)
#
In Figure \ref {fig:fig1}, we see a scatter plot.
<<fig1, echo=FALSE,fig.cap=cap, fig.scap=scap,fig.pos="!h", >>=
r<-rnorm(100)
plot(r)
#
%THIS IS THE PDF WORK AROUND
%Loading R Packages
<<loading,include=FALSE>>=
require(extrafont)
require(graphicx)
font_install("fontcm") #this gets the cm roman family from package extrafont for pdf output in r to match latex
#
<<fig-pdf,echo=FALSE, include=FALSE,fig.cap=paste("This is a Caption"),fig.pos="!h", >>=
Sys.setenv(R_GSCMD="C:/Program Files/gs/gs9.15/bin/gswin64c.exe") #this needs to go inside every r code chunk to call GhostScript for embedding latex font "computer modern roman" (so R font in pdfs matches latex document font)
pdf("tikz-plot-pdf.pdf", family="CM Roman")
set.seed(2015)
r<-rnorm(100)
plot(r)
dev.off()
embed_fonts("tikz-plot-pdf.pdf") #this embeds the pdf font so that when graphicx calls the pdf the fonts from R to latex match
#
\newpage
In Figure \ref{fig:scatter}, we see a scatter plot.
\begin{figure}[!h]
\centering
\includegraphics[width=\textwidth]{tikz-plot-pdf}
\caption{This is also a Caption}\label{fig:scatter}
\begin{minipage}{\textwidth}
NOTE: Here is a note with one linebreak from above.\\
SOURCE: Here is my source with an extra linebreak to separate it.\\
EXTRA:{\tiny EXTRA: Here is smaller text. You could explore more text sizing in \LaTeX.} And bigger again.
\end{minipage}
\end{figure}
\end{document}
I would like to have the "NOTE" and "SOURCE" lines below the caption line, EDIT 1: only the caption included in the \listoffigures and the caption centered, while the NOTE and SOURCE are left justified (like the output from the pdf workaround):
I have not asked a question on this forum before, although I have found many answers, so any meta-feedback on my question EDIT 1: or how I am editing is also appreciated.
Thank You
This answer assumes that multiline captions are sufficient for your purposes. I used your method of passing an R variable to the Knitr fig.cap= argument. This lets us compose the caption ahead of time in other code chunks before use.
The tricks were that A) we need to find out how to add line break to caption without using caption package, and B) know how to pass literal "\" (backslash) characters to the resulting Latex document.
The reference about adding captions suggests adding \\\hspace{\textwidth} to start a new line within the caption (in the Latex file). So, we escape it in the Knitr file like this \\\\\\hspace{\\textwidth}.
Indeed, almost any Latex code you want to end up in the Latex file will have to be escaped this way. When writing your thesis, you'll want to refer to your Figures, no doubt. You can use the Latex references by putting the figure \label into the caption and then using a \ref{} elsewhere.
See the modified version of your file below for multiline captions and figure references:
\documentclass[12pt]{article}%12 Pt font, article document class
\usepackage{caption}
\usepackage{tikz}%Draw Graphs
\begin{document}
<<>>=
x <- paste(
"This is a Caption.",
"\\\\\\hspace{\\textwidth}",
"NOTE: Here is a note with one linebreak from above.",
"\\\\\\hspace{\\textwidth}",
"\\\\\\hspace{\\textwidth}",
"SOURCE: Here is my source with an extra linebreak to separate it.",
"\\\\\\hspace{\\textwidth}",
"{\\tiny EXTRA: Here is smaller text. You could explore more text sizing in \\LaTeX.} And bigger again.",
"\\label{figure:demo-of-multiline-captions}",
"\n" )
cat(x)
#
We can also show the variable "x" in the "asis" formate here:
<<results="asis">>=
cat(x)
#
This text right here (now) is a new paragraph, so it is indented.
Below, in \textbf{Figure~\ref{figure:demo-of-multiline-captions}}, we use the "x" variable in the "fig.cap=" argument to Knitr.
<<fig1, echo=FALSE,fig.cap=x,fig.pos="!h", >>=
r<-rnorm(100)
plot(r)
#
\end{document}
Results give this:

Adding a table of contents to PDF with R plots

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.

Resources