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

如何为4行2列合并图像中的8幅子图添加a)-h)标注

解决方案

要为合并后的子图添加a)-h)标注,核心思路是先给单张子图添加标注,再进行合并布局。以下是修正后的完整代码,同时修正了原代码的布局逻辑(原代码生成的是2行4列,调整为符合需求的4行2列):

library(magick)

# 输入文件路径列表
file_list <- c("D:/Graphs/NL.tiff", "D:/Graphs/LA.tiff", "D:/Graphs/LFW.tiff", "D:/Graphs/LDW.tiff",
               "D:/Graphs/SL.tiff", "D:/Graphs/SG.tiff", "D:/Graphs/NB.tiff", "D:/Graphs/SFW.tiff")
# 输出文件名称
output_file <- "merged_graphs_with_labels.tiff"

# 定义子图标注文本
labels <- c("a)", "b)", "c)", "d)", "e)", "f)", "g)", "h)")

# 带标注的图像合并函数
merge_and_save_with_labels <- function(files, output_file, labels) {
  # 读取所有图像
  images <- image_read(files)
  n_images <- length(images)
  
  # 参数校验
  if (n_images != length(labels)) {
    stop("图像数量与标注数量必须一致")
  }
  if (n_images != 8) {
    stop("必须提供恰好8张图像以生成4行2列布局")
  }
  
  # 为每张图像添加标注
  labeled_images <- mapply(function(img, label) {
    # 可根据图像尺寸调整以下参数:size(字体大小)、location(标注位置)
    image_annotate(img, 
                   text = label,
                   size = 20,        # 字体大小,按需修改
                   color = "black",  # 标注颜色
                   location = "+10+10",  # 左上角偏移:向右10px,向下10px
                   font = "Arial",   # 字体类型
                   weight = 700      # 字体加粗(可选)
                   )
  }, images, labels, SIMPLIFY = FALSE)
  
  # 构建4行2列布局
  # 第一列:第1、3、5、7张图垂直堆叠
  col1 <- image_append(labeled_images[c(1, 3, 5, 7)], stack = TRUE)
  # 第二列:第2、4、6、8张图垂直堆叠
  col2 <- image_append(labeled_images[c(2, 4, 6, 8)], stack = TRUE)
  # 合并两列得到最终图像
  combined_image <- image_append(c(col1, col2), stack = FALSE)
  
  # 保存合并后的图像
  image_write(combined_image, path = output_file, format = "tiff")
}

# 执行合并
merge_and_save_with_labels(file_list, output_file, labels)

关键调整说明

  • 标注添加:通过mapply遍历每张图像和对应标注,使用image_annotate在指定位置插入文本。可根据你的图像尺寸,调整size(字体大小)、location(偏移量,+x+y表示从左上角向右x像素、向下y像素)等参数。
  • 布局修正:原代码的逻辑生成的是2行4列,修正为4行2列:先将奇数位图像垂直堆叠为第一列,偶数位图像垂直堆叠为第二列,再将两列水平合并。
  • 可选优化:如果需要将标注放在右上角,可动态获取图像宽度计算位置,示例代码如下:
    labeled_images <- mapply(function(img, label) {
      img_info <- image_info(img)
      # 右上角偏移:右移50px,向下10px
      location <- paste0("+", img_info$width - 50, "+10")
      image_annotate(img, 
                     text = label,
                     size = 20,
                     color = "black",
                     location = location,
                     font = "Arial",
                     weight = 700
                     )
    }, images, labels, SIMPLIFY = FALSE)
    

内容的提问来源于stack exchange,提问作者ORBITTING ARYABHATA

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 19:40:34