我正在嘗試使用 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'))
```
上面的程式碼產生兩個堆疊圖像,帶有兩個單獨(相同)的標題:
當Fig.cap呼叫被刪除時,圖形正確對齊,但沒有標題。
如何更改我的程式碼區塊,以便圖像並排對齊且僅顯示單一標題?
答案1
我找到了解決此問題的方法,方法是在同一繪圖視窗中將 .png 影像繪製為光柵:
```{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])
```