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

Knitr设置:显示代码不输出图形+单图形文件输出需求

knitr在Rnw Beamer中的两个配置问题解决方案

1. 显示代码但不生成嵌入图形,同时保留图形文件

include=FALSE会彻底隐藏代码块的所有内容,不符合需求。改用以下选项组合:

  • echo=TRUE:确保代码块内容在幻灯片中正常显示
  • fig.show='hide':不在当前幻灯片中嵌入图形,但会正常生成图形文件到指定路径
  • 可选使用fig.path指定图形输出目录(比如fig.path='slides_figs/'),方便后续插入时查找

2. 强制单代码块生成单个图形文件

默认情况下,代码块里每一条绘图指令都会生成独立的图形文件。要合并成单个文件,分两种场景处理:

Base绘图场景

用par()设置多图布局,把所有绘图内容放在同一个画布中:

# 设置2行1列的布局
par(mfrow = c(2, 1))
plot(1:10, main="线性趋势")
plot(rnorm(50), main="随机分布")
# 恢复默认布局(避免影响后续代码)
par(mfrow = c(1, 1))

ggplot2绘图场景

使用gridExtra::grid.arrange()将多个ggplot对象合并为单个图形:

library(ggplot2)
library(gridExtra)

p1 <- ggplot(mtcars, aes(mpg, disp)) + geom_point()
p2 <- ggplot(mtcars, aes(hp, qsec)) + geom_point()

# 合并为2行1列的图形
grid.arrange(p1, p2, nrow = 2)

完整最小示例Rnw代码

\documentclass{beamer}
\begin{document}

\begin{frame}[fragile]
\frametitle{代码展示(无嵌入图形)}
<<echo=TRUE, fig.show='hide', fig.path='beamer_figs/', fig.width=7, fig.height=5>>=
# 示例:单代码块生成单个图形文件
par(mfrow = c(2, 1))
plot(1:10, col="darkred", lwd=2)
plot(rnorm(100), col="steelblue", pch=16)
par(mfrow = c(1, 1))
@
\end{frame}

\begin{frame}
\frametitle{插入生成的图形}
\includegraphics[width=\textwidth]{beamer_figs/unnamed-chunk-1.pdf}
\end{frame}

\end{document}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 12:56:09