r - knitr 绘制要查看和运行的代码块

标签 r knitr

我一直在尝试使用 knitr 解决以下问题。 在 \LaTeX 中,我希望定义一个名为 myplot 的 block (一次)。 那我想说一句比如:

代码

<<myplot, tidy = FALSE>>=
plot(runif(9), runif(9),
     xlab = "x",
     ylab = "y",)
@

结果在 Figure~\ref{fig:myownlabel} 中。

\begin{figure}[hh]
\begin{center}
<<myplotfig, out.width='.50\\linewidth', width=6.6, height=4.8, echo=FALSE>>=
par(las = 1, mfrow = c(1, 1), mar = c(5, 4, 1, 1)+0.1)
<<myplot>>
@
\caption{
I insist to have the caption in \LaTeX.
\label{fig:myownlabel}
}
\end{center}
\end{figure}

我知道如何在 Sweave 中执行此操作,但似乎无法在 knitr 中执行此操作。 也就是说,代码块是读者看到的。 你能给我什么建议吗? 提前致谢。 托马斯

最佳答案

这是 knitr 和 Sweave 之间的一个区别:默认情况下 Sweave 不保留绘图(除非您指定 fig=TRUE),但是 knitr 会(除非您真的不想要它们,使用 fig.keep='none')。

<<myplot, tidy = FALSE, fig.keep = 'none'>>=
plot(runif(9), runif(9),
     xlab = "x",
     ylab = "y",)
@

\begin{figure}[hh]
\begin{center}
<<myplotfig, out.width='.50\\linewidth', fig.width=6.6, fig.height=4.8, echo=FALSE>>=
par(las = 1, mfrow = c(1, 1), mar = c(5, 4, 1, 1)+0.1)
<<myplot>>
@
\caption{
I insist to have the caption in \LaTeX.
\label{fig:myownlabel}
}
\end{center}
\end{figure}

虽然到目前为止问题已经解决,但我还有几点意见:

  1. 当您使用 knitr (>= 1.1) 时,您应该能够看到有关代码块语法的警告,并且您需要调用 Sweave2knitr() 解决问题;你会意识到 widthheightknitr 中不是有效的 block 选项(使用 fig.width图.height);见here for more information
  2. 对于代码块 myplot,我会使用 eval=FALSE,因为您可能不想对代码求值两次;
  3. 使用 knitr,您实际上可以通过 block 选项做任何事情,例如

    <<myplot, tidy=FALSE, eval=FALSE, echo=-1>>=
    @
    <<myplot, out.width='.5\\linewidth', fig.width=6.6, fig.height=4.8, fig.align='center', echo=FALSE, fig.pos='hh', fig.cap='I insist to have the caption in \\LaTeX.'>>=
    par(las = 1, mfrow = c(1, 1), mar = c(5, 4, 1, 1)+0.1)
    plot(runif(9), runif(9),
         xlab = "x",
         ylab = "y",)
    @
    

    这会为您提供 centerfigure 环境,并自动生成标签 fig:myplot

关于r - knitr 绘制要查看和运行的代码块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18069463/

相关文章:

r - 内连接,看不到列

sql-server - 如何在 R 中连接到 SQL Server 数据库

r - 使用knitr在附录中显示代码

R:将增加的值子集到最大值,不包括减少的值

r - 如何将 R 矩阵转换为 xts/zoo 对象?

r - 如何使用pandoc将目录添加到R Markdown HTML文件中?

r - 如何删除 kable 表格 HTML 行 strip ?

r-markdown - Reveal.js 中的左边距过大

r - R Caret 包中的逻辑回归调整参数网格?

r - 使用RMarkdown + knitr以条件格式创建表