I'm using Rmarkdownv2 to generate a pdf file with some local images. But it seems that the image was converted to a larger size with lower resolution in the rendered pdf, compared to the html. The code I'm currently using for the image is something like:
![alt text](figures/fig1.png)
Is there any way to control the image size in the pdf? I also tried
pdf_document:
fig_height: 1
fig_width: 2
But that didn't work. Thanks in advance.
You can use the development version of knitr (>= v1.11.22) and the include_graphics() function, e.g.
```{r out.width='70%'}
knitr::include_graphics('figures/fig1.png')
```
If you want a figure caption, just use the chunk option fig.cap = 'A figure caption.'
Related
I think the question is quite self-explanatory but for avoidance of doubt I'll explain with more detail below:
I have an R Markdown document that works well if converted to HTML or uploaded to GitHub. When converting to PDF (using Latex), the results are not so pretty. I find that the biggest problem in a Latex PDF document are line breaks. I can fix the line breaks issue on the PDF document by adding "\ " characters, but that throws my HTML document out of whack too.
Is there a way to manually add line breaks (or "space before/after paragraphs") for the PDF output only?
Thank you!
You can redefine the relevant spacings in the YAML header. \parskip controls the paragraph spacing. Code blocks are shaded using a snugshade environment from the framed package. We can also redefine the shaded environment for code blocks to have some vertical space at the start. Here's a reproducible example. Note: I also added the keep_tex parameter so you can see exactly what the generated tex file looks like, in case this is useful:
title: "test"
author: "A.N. Other"
header-includes:
- \setlength{\parskip}{\baselineskip}
- \renewenvironment{Shaded}{\vspace{\parskip}\begin{snugshade}}{\end{snugshade}}
output:
pdf_document:
keep_tex: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
Once you output to HTML, you can just print the HTML webpage as PDF. that might be an easy way keep the original format
I am using RMarkdown to create a html file (my preferred format). I then use the officer package to create a powerpoint (PPT) (everyone else's preferred format) that reads in the .png images that are automatically created and saved when I knit the document (I believe this is default when the fig.path is specified).
To get consistent fontsize throughout the PPT figures, I have specified in each knitr chunk fig.width, out.width, etc to be equal to the relevant PPT placeholder dimensions. E.G if the PPT placeholder is 5.29in high x 5.89in wide, then in the knitr chunk I specify , out.height="5.29in", out.width="5.89in", fig.height=5.29, fig.width=5.89). This seems to work in terms of the PPT file, however it results in extremely small figures for the HTML file. Is there a way to get the knitr code to work for both html and PPT, without needing to specifically save the image, using, for example ggsave()?
Following is some auto-generated test code:
---
title: "Test_Figure_Size"
output:
html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(fig.path = "Delete_Me/", echo=FALSE)
```
When you include out.height, out.width the figure is extremely small in the knitted html document, but perfectly sized as a .png file.
```{r pressure, echo=FALSE, out.height="5.29in", out.width="5.89in", fig.height=5.29, fig.width=5.89}
plot(pressure)
```
When you say out.height="5.29in", out.width="5.89in", those values are written into the HTML output as height and width attributes of the img. But height and width are expressed in pixels, so you'll end up with a figure about 5 pixels square.
I don't use Powerpoint, but is there a way to specify the image size in pixels, e.g. "589px" or something similar? Then it will use the same scale as the browser, and things should be consistent.
I am quite excited about the upcoming RStudio notebooks (available in the preview version of RStudio. For a short overview click here). However, I am encountering some difficulties with including images.
In Rmarkdown, I can include images like this:
---
title: "This works"
output: html_document
---
```{r echo=FALSE, out.width='10%'}
library(knitr)
knitr::include_graphics('https://www.rstudio.com/wp-content/uploads/2014/06/RStudio-Ball.png')
```
However, when I want to do the same in a notebook (note the change from html_document to html_notebook), I no longer get an image:
---
title: "This does not work"
output: html_notebook
---
```{r echo=FALSE, out.width='10%'}
knitr::include_graphics('https://www.rstudio.com/wp-content/uploads/2014/06/RStudio-Ball.png')
```
(When I use an image in the same folder as my notebook, I simply get the name of that image, just as is the case with the link to the external image).
My question: is there a way to display the image also in the notebook (update:) inside a rmarkdown code-chunk?
Please note: I want to use r-code to include the image. I do not want to include images with standard markdown (![image description](path/to/image)), which works in both the notebook and the regular rmarkdown document. I also do not want to use html. My hope would be that using r-code to include the image would render the image in the notebook.
Edit: One difference between regular Rmarkdown files and notebooks is that notebooks are "previewed" and not knit:
Thanks for taking the time to try out the notebooks. There is a roundabout way you can do this today; just make a plot and draw the image on it.
download.file("https://www.rstudio.com/wp-content/uploads/2014/06/RStudio-Ball.png", "RStudio-Ball.png")
library("png")
ball <- readPNG("RStudio-Ball.png", native = TRUE)
plot(0:1, 0:1, type = "n", ann = FALSE, axes = FALSE)
rasterImage(ball, 0, 0, 1, 1)
It's a bit of a hack, though, so we just added support for knitr::include_graphics. It'll be in tomorrow's daily (0.99.1272 or later).
I'm producing a solutions manual for a book, using .Rmd files with the following YAML header:
---
title: "DDAR: Solutions and Hints for Exercises"
date: "`r Sys.Date()`"
output:
word_document:
reference_docx: solutions-setup.docx
---
where I control the general layout of the document with the reference_docx to get an output Word document.
There will be many figures, and I'd like to set some global graphics parameters to give relatively tight bounding boxes and reasonable font sizes
in the figures without having to tweak each one from what I see in a PDF document.
I tried the following, but the par() setting doesn't seem to have any effect:
{r setup, echo=FALSE}
options(digits=4)
par(mar=c(5,4,1,1)+.1)
Instead I get images like the following in my document with larger bounding boxes than I would like and with much larger font sizes than I would like.
I know how to control all this in .Rnw files produced with LaTeX, but I
can't find how to do it in .Rmd -> Word. Is there a chunk hook I could
use? I don't think that there is an out.width chunk option that re-scales
a figure as in LaTeX.
#scoa's answer shows how to use a hook to set some graphical parameters at the beginning of each chunk. This is necessary because "by default, knitr opens a new graphics device to record plots and close it after evaluating the code, so par() settings will be discarded", i.e. graphical parameters for later chunks cannot be set in an early setup-chunk but need to be set for each chunk separately.
If this behavior is not wanted, the package option global.par = TRUE can be used:
opts_knit$set(global.par = TRUE)
Finding the correct values for the margins is sometimes quite painful. In these cases, hook_pdfcrop can help. In all chunks where the option crop = TRUE, white margins will be removed. To apply this to all chunks, use
library(knitr)
knit_hooks$set(crop = hook_pdfcrop)
opts_chunk$set(crop = TRUE)
This works for docx output as well because "when the plot format is not PDF (e.g. PNG), the program convert in ImageMagick is used to trim the white margins" (from ?hook_pdfcrop).
Note that under some circumstances, cropping plots has the side effect of sometimes apparently different "zoom" factors of plots: This happens in cases where we start with identical sized elements on two plots but larger white margins around one of the plots. If then both are resized to a fixed output width after cropping, elements on the plot with larger margins look larger. However, this is not relevant for docx output because out.width/out.height cannot be used in that case.
The knitr documentation for hooks actually uses small margins as an example of what you can do with hooks. Here is a solution (adapted from this documentation).
---
output: word_document
---
```{r setup, echo=FALSE}
library(knitr)
knit_hooks$set(small.mar = function(before, options, envir) {
if (before) par(mar=c(5,4,1,1)+.1) # smaller margin on top and right
})
opts_chunk$set(small.mar=TRUE)
```
```{r}
plot(iris$Sepal.Length)
```
Using opts_chunk$set(small.mar=TRUE) is a way to avoid passing it to every chunk in the document.
The margin appears fixed (screenshot from the docx output in libreoffice with default reference-docx).
I am trying to insert logo into beamer presenation using Rmarkdown, and it looks like size controls in \logo{\includegraphics[height=1cm,width=3cm]{logo.png}} do not work, no matter what values I put there, image is always of the same size. Any suggestions besides modifying image manually?
---
title: "Presentation"
author: "Author"
output:
beamer_presentation:
includes:
in_header: mystyle.tex
---
## R Markdown
This is an R Markdown presentation. Markdown is a simple formatting
syntax for authoring HTML, PDF, and MS Word documents. For more
details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that
includes both content as well as the output of any embedded R code
chunks within the document.
## Slide with Bullets
- Bullet 1
- Bullet 2
- Bullet 3
## Slide with R Code and Output
```{r}
summary(cars)
```
## Slide with Plot
```{r, echo=FALSE}
plot(cars)
```
This is mystyle.tex
\logo{\includegraphics[height=1cm,width=3cm]{logo.png}}
\usetheme{Madrid}
\usefonttheme{serif}
\institute{Institute}
\setbeamertemplate{navigation symbols}{}
UPDATE: Quick work around - simply modifying image will not work - image is ugly and pixelated. Simply converting to pdf also didn't work well, so I used following R code to create pdf and use it in \logo{\includegraphics{logo.pdf}}
library(png)
library(grid)
img <- readPNG('logo.png')
img <- rasterGrob(img, interpolate=TRUE)
pdf(file = 'logo.pdf', width = 1, height = 0.25)
grid.newpage()
grid.raster(img)
dev.off()
I found solution; in beamer manual there is another way of using logo function and it works fine.
\pgfdeclareimage[height=0.2787cm, width=2.5cm]{logo}{logo.png}
\logo{\pgfuseimage{logo}}
I found this beamer tutorial quite useful. Just add the following to the file mystyle.tex passed to the YAML option in_header (as shown in the question):
\usepackage{tikz}
\titlegraphic {
\begin{tikzpicture}[overlay,remember picture]
\node[left=0.2cm] at (current page.30){
\includegraphics[width=3cm]{Beamer-Logo}
};
\end{tikzpicture}
}
and then you can play around with the node parameters to adjust the placement of your logo (Beamer-Logo).