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

使用rmarkdown::render()生成PDF时LaTeX编译失败求助

问题:R Markdown渲染PDF失败(关联ggplot代码)

执行渲染命令:

rmarkdown::render("Code/AnalyzeDataMFSQuant.R", "pdf_document")

出现报错:

Package pdftex.def Error: File 'AnalyzeDataMFSQuant_files/figure-latex/Things (Gifts, art, cards, jewellery, family heirlooms)-1.pdf' not found: using draft setting

最终LaTeX编译失败。其他R脚本可正常渲染,仅包含以下ggplot代码时出现问题:

ggplot(MFS_RespondentLevelOfConfidenceInSouvenirReachingHeirs, aes(x = HowConfidentDescendantsWillFind, y = PctInterested)) +
  geom_bar(stat = "identity", fill = "skyblue") +
  labs(title = "Percentage of people who believe in souvenir naturally reaching heirs ",
       x = "Level of confidence (1= No confidence, 5=full confidence)",
       y = "Pct of respondents") +
  scale_y_continuous(labels = scales::percent_format(scale = 1)) +
  theme_minimal()
解决方案
  • 问题本质:LaTeX对文件名中的空格、括号等特殊字符兼容性差,自动生成的图片文件名包含这些字符,导致pdftex无法定位文件。

  • 方法1:手动指定图片文件名
    将ggplot对象赋值给变量,用ggsave()输出到不含特殊字符的文件,再手动插入到文档中:

    # 生成图表对象
    p <- ggplot(MFS_RespondentLevelOfConfidenceInSouvenirReachingHeirs, aes(x = HowConfidentDescendantsWillFind, y = PctInterested)) +
      geom_bar(stat = "identity", fill = "skyblue") +
      labs(title = "Percentage of people who believe in souvenir naturally reaching heirs ",
           x = "Level of confidence (1= No confidence, 5=full confidence)",
           y = "Pct of respondents") +
      scale_y_continuous(labels = scales::percent_format(scale = 1)) +
      theme_minimal()
    
    # 保存为安全文件名
    ggsave("figure_confidence_heirs.pdf", plot = p, device = "pdf")
    

    在文档中插入图片:

    ![受访者对传家宝到达后代的信心比例](figure_confidence_heirs.pdf)
    
  • 方法2:全局设置替换特殊字符
    在R Markdown的YAML头部添加配置,自动将图片文件名中的特殊字符替换为下划线:

    output:
      pdf_document:
        fig.path: "AnalyzeDataMFSQuant_files/figure-latex/"
        fig.process: "function(x) gsub('[^a-zA-Z0-9_]', '_', x)"
    
  • 方法3:代码块级别指定文件名
    在包含ggplot的代码块中设置fig.name为不含特殊字符的名称:

    ```{r fig.name="confidence_heirs"}
    ggplot(MFS_RespondentLevelOfConfidenceInSouvenirReachingHeirs, aes(x = HowConfidentDescendantsWillFind, y = PctInterested)) +
      geom_bar(stat = "identity", fill = "skyblue") +
      labs(title = "Percentage of people who believe in souvenir naturally reaching heirs ",
           x = "Level of confidence (1= No confidence, 5=full confidence)",
           y = "Pct of respondents") +
      scale_y_continuous(labels = scales::percent_format(scale = 1)) +
      theme_minimal()
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 00:45:15