gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:49:29 26 4
gpt4 key购买 nike

我一直在尝试使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com