You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

bookdown跨PDF/DOCX/HTML输出自定义宽度带标签子图的实现问询

你可以使用flextable包替代原生子图逻辑实现三种格式的兼容输出,具体操作如下:

1. 安装依赖包

install.packages(c("flextable", "officer", "magrittr", "png", "jpeg"))

2. 修改后的Rmd完整代码

---
title: Three images
site: bookdown::bookdown_site
output:
  bookdown::pdf_document2: default
  bookdown::word_document2: default
  bookdown::html_document2: default
---
```{r, echo=FALSE, warning=FALSE, message=FALSE}
library(flextable)
library(officer)
library(magrittr)

# 配置图片路径和对应宽度(单位mm)
img_paths <- c("img/10mm.png", "img/20mm.jpg", "img/30mm.jpg")
target_width_mm <- c(10, 20, 30)

# 自动计算各图片保留比例的对应高度
get_img_ratio <- function(path) {
  if (grepl("\\.png$", path)) {
    img <- png::readPNG(path, native = FALSE)
  } else if (grepl("\\.jpg$|\\.jpeg$", path)) {
    img <- jpeg::readJPEG(path, native = FALSE)
  }
  return(nrow(img)/ncol(img))
}
img_ratios <- sapply(img_paths, get_img_ratio)
target_width_inch <- target_width_mm / 25.4
target_height_inch <- target_width_inch * img_ratios

# 构造子图和子标签表格内容
fig_row <- data.frame(
  col1 = as_paragraph(as_image(src = img_paths[1], width = target_width_inch[1], height = target_height_inch[1])),
  col2 = as_paragraph(as_image(src = img_paths[2], width = target_width_inch[2], height = target_height_inch[2])),
  col3 = as_paragraph(as_image(src = img_paths[3], width = target_width_inch[3], height = target_height_inch[3])),
  stringsAsFactors = FALSE
)
label_row <- data.frame(
  col1 = "(a)",
  col2 = "(b)",
  col3 = "(c)",
  stringsAsFactors = FALSE
)
table_data <- rbind(fig_row, label_row)

# 生成无格式表格,适配三种输出
subfig_table <- flextable(table_data, col_keys = c("col1", "col2", "col3")) %>%
  delete_part(part = "header") %>%
  width(width = target_width_inch) %>%
  align(align = "center", part = "all") %>%
  border_remove() %>%
  set_caption(
    caption = "Three images with different widths – 10 mm (a), 20 mm (b), 30 mm (c)",
    autonum = run_autonum(seq_id = "fig", bkm = "fig:subfig")
  )

subfig_table

子图效果见 Fig. @ref(fig:subfig)

### 适配效果说明
- 三种输出格式下图片宽度严格遵循设置的10/20/30mm,保留原始比例无拉伸
- 子标签(a)(b)(c)自动对齐对应子图,总标题支持正常交叉引用
- 无需额外引入LaTeX包,兼容你当前使用的R 3.4运行环境

内容的提问来源于stack exchange,提问作者N0rbert
相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 21:15:04