[Tex/LaTex] Including multiple images with single caption

knitrpandocr

I'm trying to insert side-by-side images with one caption using knitr:

---
title: "XY"
author: "Doogan"
date: '`r format(Sys.Date(), "%B %d, %Y")`'
graphics: yes
output:
pdf_document:
  toc: no
  fig_caption: true
fontsize: 11pt
geometry: margin=1cm
---

```{r Directory, echo=F, message=F, warning=FALSE, paged.print=TRUE}

image.dir <- "your/directory/"
knitr::opts_chunk$set(echo = FALSE)

```

```{r 'xy_images' 
,fig.show='hold',fig.pos='H',out.height='7.5cm',out.width='10cm',fig.cap="X 
image (A) and Y image (B)"}

knitr::include_graphics(file.path(image.dir, 'X.png'))
knitr::include_graphics(file.path(image.dir, 'Y.png'))

```

The above code produces two stacked images with two separate (identical) captions:

enter image description here

When the fig.cap call is removed, the figures align correctly, but with no caption.

How can I alter my code chunk so that the images align side-by-side with only a single caption displayed?

Image used: enter image description here

Best Answer

I found a work around to this issue by plotting the .png images as rasters in the same plot window:

```{r 'xy_images', fig.width = 8,fig.height = 4.5, 
    fig.show='hold',fig.pos='H'fig.cap="X image (A) and Y image (B)"}


library(png);library(raster)

X <-readPNG("X.png")
Y <-readPNG("Y.png")

#set up figure
par(mar=c(0,0,0,0), xpd=NA, mgp=c(0,0,0), 
    oma=c(0,0,0,0), ann=F, mfrow = c(1,2))
plot.new()
usr<-par("usr")

#fill plot with images
rasterImage(X, usr[1], usr[3], usr[2], usr[4])
rasterImage(Y, usr[1]+1.1, usr[3], usr[2]+1.1, usr[4])

```