Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert side by side png images using knitr

Tags:

markdown

r

knitr

How can I insert side by side png files from my computer into rstudio when creating an html document?

The following works well (plots)

```{r, echo=FALSE,fig.width=4, fig.show='hold'}  plot(cars) plot(rnorm(100)) ``` 

But for images from a path, only the last image is displayed

 ```{r fig.width=3, fig.show='hold'}    library(png)   img <- readPNG("C:/path to my picture/picture.png")   grid.raster(img)    img2 <- readPNG("C:/path to my picture/picture2.png")   grid.raster(img2)   ``` 
like image 950
Salvador Avatar asked Aug 20 '14 22:08

Salvador


People also ask

How do I put figures side by side in R markdown?

In a . Rmd document there are several ways to produce figures side-by-side. If the figures already exist, the easiest way for me is to use knitr::include_graphics(c(fig1, fig2, ...)) [Thx: Yihui!]

Can you insert images in R markdown?

To insert an image, you can also use an R code chunk. --- title: "R Markdown Tips and Tricks" output: html_document --- You can also insert an image using R code: ```{r} knitr::include_graphics("img/rmarkdown_hex. png") ``` The image looks smaller by default though.

How does R knitr work?

When you run render , R Markdown feeds the . Rmd file to knitr, which executes all of the code chunks and creates a new markdown (. md) document which includes the code and its output. The markdown file generated by knitr is then processed by pandoc which is responsible for creating the finished format.

What is the function of knitr in creating markdown document?

knitr is an engine for dynamic report generation with R. It is a package in the programming language R that enables integration of R code into LaTeX, LyX, HTML, Markdown, AsciiDoc, and reStructuredText documents. The purpose of knitr is to allow reproducible research in R through the means of literate programming.


2 Answers

You can use knitr::include_graphics() as this one accepts a vector of paths as an argument.

Then you should use fig.show='hold',fig.align='center' in order to plot them on the same line and out.width="49%", out.height="20%" to control the output size.

```{r, echo=FALSE,out.width="49%",  out.height="20%",fig.cap="caption",fig.show='hold',fig.align='center'} knitr::include_graphics(c("path/to/img1","path/to/img1")) ```  
like image 125
Marc Bataillou Avatar answered Sep 22 '22 19:09

Marc Bataillou


You should learn the syntax of Markdown (really, you need about five minutes). The solution does not even involve R at all:

![](path/to/picture.png) ![](path/to/picture2.png) 

BTW, you'd better avoid absolute paths. Use relative paths (relative to your Rmd file).

like image 37
Yihui Xie Avatar answered Sep 23 '22 19:09

Yihui Xie