insert side by side png images using knitr

2019-02-08 06:52发布

问题:

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

回答1:

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



回答2:

We still lack a good answer to this question if the desired output is a MS Word document (I see that the OP specifically asked for HTML output, but I'm guessing I'm not the only one who came here looking for a solution that works for MS Word docs also).

Here's one method, based on this and this, but the result is not very satisfactory:

library(png)
library(grid)
library(gridExtra)
img1 <-  rasterGrob(as.raster(readPNG("path/to/picture1.png")), interpolate = FALSE)
img2 <-  rasterGrob(as.raster(readPNG("path/to/picture2.png")), interpolate = FALSE)
grid.arrange(img1, img2, ncol = 2)


标签: r markdown knitr