Less pixelated plots in RMarkdown2 - r

I want to plot a qplot() + geom_smooth() using a knitr code chunk in an .Rmd document that I am compiling as an ioslides presentation, and I want less pixelation. I've played with ggsave() and inserting the resulting .png using ![image][id], but of course the image is massive. Can I change the image size within the RMarkdown image tag? Is there some more optimal solution? Thank you.

Set your dev to something scalable:
opts_chunk$set(
dev = c('png', 'postscript') # produce both png and ps versions
);

Related

Low quality figures using RMD to create latex docs

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}$")

How to remove automatic width assignment in \includegraphics from Rmarkdown?

I'm using Rmarkdown to create pdf files. I have chunks inside the .Rmd file like this one:
```{r}
knitr::include_graphics('image.png')
```
This is converted in the .tex file to:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{knitr}\OperatorTok{::}\KeywordTok{include_graphics}\NormalTok{(}\StringTok{'image.png'}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\includegraphics[width=8.88in]{image}
Unfortunately, in most cases that I've seen the width is not appropriate. How to automatically remove the "[width=8.88in]" ? On an other computer the width was not set like this, even with the same .Rmd file, and the images had the appropriate size.
But I cannot figure where this difference comes from, as I do not have access to this computer anymore.
Thank you
Please see the argument dpi on the help page ?knitr::include_graphics. In short:
knitr::include_graphics('image.png', dpi = NA)
Or manually specify a width via the out.width chunk option.

R markdown: can I insert a pdf to the r markdown file as an image?

I am trying to insert a pdf image into an r markdown file. I know it is possible to insert jpg or png images. I was just wondering if it is also possible to insert a pdf image. Thanks very much!
If you are just trying to insert an image that has been exported from, for example, some R analysis into a pdf image, you can also use the standard image options from the knitr engine.
With something like:
```{r, out.width="0.3\\linewidth", include=TRUE, fig.align="center", fig.cap=c("your caption"), echo=FALSE}
knitr::include_graphics("./images/imagename.pdf")
```
Unfortunately you can't specify the initial dimensions of your image output (fig.width and fig.height), which you would need to pre-define in your initial output, but you can specify the ultimate size of the image in your document (out.width). As noted below, however, this is limited to scaling down.
You could also of course leave out the initial directory specification if your files are in the same working directory. Just be aware of operating system differences in specifying the path to the image.
An alternative method is to use Markdown syntax noted by #hermestrismegistus on this post:
![Image Title](./path/to/image.pdf){width=65%}
This can also be collected for multiple images side-by side:
![Image Title](./path/to/image.pdf){width=33%}![Image2 Title](./path/to/image2.pdf){width=33%}![Image3 Title](./path/to/image3.pdf){width=33%}
Edit:
After working more extensively with in-text referencing, I have found that using r chunks and the include_graphics option to be most useful. Also because of the flexibility in terms of image alignment (justification).
As an example:
```{r image-ref-for-in-text, echo = FALSE, message=FALSE, fig.align='center', fig.cap='Some cool caption', out.width='0.75\\linewidth', fig.pos='H'}
knitr::include_graphics("./folder/folder/plot_file_name.pdf")
```
The reference can later be used in-text, for example, Figure \#ref(fig:image-ref-for-in-text) illustrates blah blah.
Some important things to note using this format:
You can only expand PDF images via a code chunk up to the out.width and out.height conditions set in the original .pdf file. So I would recommend setting them slightly on the larger side in your original image (just note that any chart text will scale accordingly).
The in-text reference code (in this case image-ref-for-in-text) CANNOT contain any underscores (_) but can contain dashes (-). You will know if you get this wrong by an error message stating ! Package caption Error: \caption outside float.
To stop your plots drifting to the wrong sections of your document, but in a way that unfortunately will generate some white space, the above example includes fig.pos='H'. Where H refers to "hold" position. The same can be achieved for the former Markdown option by placing a full-stop (period .) immediately after the last curly bracket.
Example:
![Image Title](./path/to/image.pdf){width=75%}.
Unfortunately, this latter option results in some unsightly full-stops. Another reason I prefer the include_graphics option.
Sorry, I found that there is a similar post before:
Add pdf file in Rmarkdown file
Basically, I can use something like below works well for the html output:
<img src="myFirstAlignment2.pdf" alt="some text" width="4200" height="4200">
And something like below works well for the pdf output:
(1)possible solution
\begin{center} <br>
\includegraphics[width=8in]{myFirstAlignment2.pdf} <br>
\end{center}
(2)possible solution
![Alt](myFirstAlignment2.pdf)
The myFirstAlignment2.pdf should be replaced with path\myFirstAlignment2.pdf if the pdf file is not in your working directory.
In relation to the comment of the best answer, there is a way to use the second option, and the output not come out tiny.
Use the following syntax below with the height being a large number. Having text in the brackets is necessary for it to work.
![Alt](./file.pdf){width=100% height=400}
None of the answers outlined worked well for me in terms of sizing the pdf, so adding another answer using the code chunk options for out.height and out.width to control the size:
```{r out.height = "460px", out.width='800px', echo=F}
knitr::include_graphics("./images/imagename.pdf")
```

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"

add and resize a local image to a .Rmd file in RStudio that will produce a pdf

I am trying to add and resize a local image to a .Rmd file in RStudio that will produce a pdf. I can add the file easily with
![My caption.](path/file.png)
but I have not figured out how to control the size of the image. I tried HTML code with a width attribute, but the image would not appear (I think this only works if outputting to HTML).
<img src="path/file.png" width="200px" />
I could not get this idea to work:
![My caption.](path/file.png =250x)
Is there a way to modify the Rmarkdown script to modify the size of the local image with only RMarkdown and base R?
There is a suggestion to use the png and grid packages, but I am limited to base R for my problem. For other users, however, I think this looks like a good solution.
You can also specify the size of the image like so:
![](filepath\file.jpg){ width=50% }
The width and height attributes on images are treated specially. When used without a unit, the unit is assumed to be pixels. However, any of the following unit identifiers can be used: px, cm, mm, in, inch and %. There must not be any spaces between the number and the unit.
Source: Pandoc's RMarkdown Documentation - Images
From #tmpname12345
You can use raw latex to include a figure in pdf_output: \includegraphics[width=250pt]{path/file.png}
In case anyone arrives here from google looking to insert an image into an RMarkdown html_document:
Insert directly
This method is arguably the easiest to change size
<img src="mypic.png" alt="drawing" width="200" height="50"/>
Another way
Note you can mix measurements like so: height="200" width=60%
![some caption text here](mypic.png){height="200" width=60% }
Insert via RMarkdown chunk
knitr::include_graphics("mypic.png")
Insert directly from URL
```{r echo=FALSE, out.width = '60%'}
image_url <- "http://www.example.com/mypic.png"
```
<center><img src="`r image_url`"></center>
A longer example with latex.
\begin{figure}
\includegraphics[width=250pt]{../images/pricePlot2006_1.5.png}
\caption{Prices through time.}\label{fig:1}
\end{figure}
Other figures created in the .Rmd are numbered automatically.
```{r namedBlock, fig.cap = "Lots of cars."}
plot(mtcars)
```

Resources