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.
Related
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 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")
```
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 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)
```
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.