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

ggplot2用element_markdown设置部分加粗标题,officer导出PPT文字错位

问题原因

ggtext::element_markdown渲染的富文本标题会被rvg::dml拆解为多个独立的矢量文本片段,每个片段对应一个独立的PPT文本框,批量导出时的坐标计算误差会直接导致错位。

最优解决方案(推荐)

将标题、副标题从ggplot图表中剥离,直接作为PPT原生富文本元素插入。PPT原生富文本为统一文本框,完全不会出现拆分错位问题,批量生成稳定性最高。

示例代码

library(ggplot2)
library(officer)
library(rvg)

# 仅生成不含标题、副标题的绘图区域
p <- ggplot() + 
  geom_line(data = mtcars, 
            aes(x = mpg, y = cyl, color = am, group = am), size = 2) + 
  theme(
    panel.grid.major = element_blank(), 
    panel.grid.minor = element_blank(),
    panel.background = element_blank(), 
    axis.line = element_line(colour = "black"),
    legend.key.height = unit(0.25, "cm"),
    legend.position = c(0.85,1),
    legend.key = element_blank(),
    axis.title.x = element_blank(), 
    axis.title.y = element_blank(),
    axis.text.x = element_text(hjust=0.5),
    text = element_text(size=11, family = 'Calibri')
  ) 

# 生成图表dml对象
p_dml <- dml(ggobj = p)

# 创建PPT对象
pptx_test <- read_pptx()

pptx_test <- pptx_test %>%
  add_slide(layout = "Title and Content", master = "Office Theme") %>% 
  # 插入图表,位置下调预留标题空间
  ph_with(p_dml, ph_location(left = 0, top = 1.8, width = 5, height = 3)) %>%
  # 插入支持局部格式的原生富文本标题
  ph_with(
    value = fpar(
      ftext("Bold Title ", prop = fp_text(font.size = 16, bold = TRUE, font.family = "Calibri")),
      ftext("not bold part", prop = fp_text(font.size = 16, italic = TRUE, font.family = "Calibri"))
    ),
    location = ph_location(left = 0, top = 1, width = 5, height = 0.8)
  ) %>%
  # 插入原生副标题
  ph_with(
    value = ftext("Some Subtitle", prop = fp_text(font.size = 10.5, font.family = "Calibri")),
    location = ph_location(left = 0, top = 1.4, width = 5, height = 0.4)
  )

# 导出本地文件
print(pptx_test, '~/Desktop/test.pptx')

备选方案(标题需嵌入图表时使用)

如果必须将标题嵌入到ggplot图表内部,可以用gridtext::textbox_grob将富文本标题渲染为单一grob对象,再通过annotation_custom添加到ggplot中,dml导出时会作为整体元素不会拆分,避免错位。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:24:01