knitr-如何对齐代码并并排打印

knitr-如何对齐代码并并排打印,r,knitr,R,Knitr,是否有一种简单的方法(例如,通过chunk选项)来获得chunk的源代码及其并排生成的绘图,如第8页(除其他外) 我尝试使用了out.width=“0.5\\textwidth”,fig.align='right',这使得绘图正确地只占据了一半的页面并向右对齐,但源代码显示在它的顶部,这是正常的行为。 我想把它放在情节的左边 谢谢 示例代码: <<someplot, out.width="0.5\\textwidth", fig.align='right'>>= plot

是否有一种简单的方法(例如,通过chunk选项)来获得chunk的源代码及其并排生成的绘图,如第8页(除其他外)

我尝试使用了
out.width=“0.5\\textwidth”,fig.align='right'
,这使得绘图正确地只占据了一半的页面并向右对齐,但源代码显示在它的顶部,这是正常的行为。 我想把它放在情节的左边

谢谢

示例代码:

<<someplot, out.width="0.5\\textwidth", fig.align='right'>>=
plot(1:10)
@
=
绘图(1:10)
@

您可以在程序包性能分析或gplots的“文本打印”中显示文本

(很少)缺点:据我所知,没有语法高亮显示的可能

示例代码:

```{r fig.width=8, fig.height=5, fig.keep = 'last', echo=FALSE}
suppressMessages(library(PerformanceAnalytics))
layout(t(1:2))
textplot('plot(1:10)')
plot(1:10)
```
我认为有三种可能性

  • 对于
    beamer
    演示,我会选择
    \begin{columns}
    <代码>\end{columns}
  • 如果只有一个这样的情节:迷你页
  • 我使用了一个表(列代码和列结果)。(本例为“正常”swave)

对于这三个选项,区块选项都将具有
include=FALSE
,并且绘图将通过
\includegraphics[]{}

被“手动”放置到正确的位置。好吧,这比我预期的要复杂得多

在LaTeX方面,可以很好地控制并排盒子的对齐,这在tex.stackexchange.com上已经很好地演示了。所以我的一般策略是用LaTeX代码包装指定R块的格式化、整洁、彩色输出:(1)将其放在adjustbox环境中;(2)将块的图形输出包含在另一个adjustbox环境的右侧。为此,我需要将knitr的默认块输出钩子替换为自定义的块输出钩子,该钩子在文档的
=
块的
(2)
部分中定义

=
(1)
部分定义了一个区块挂钩,可用于在每个区块的基础上临时设置R的任何全局选项(尤其是这里的
选项(“宽度”)
)。对于一个问题和答案,只处理这个设置的一部分

最后,第
(3)
节定义了一个knitr“模板”,即每次生成并排代码块和图形时需要设置的多个选项的集合。一旦定义,它允许用户通过在块的标题中键入
opts.label=“codefig”
来触发所有必需的操作

\documentclass{article}

\usepackage{adjustbox}            %% to align tops of minipages
\usepackage[margin=1in]{geometry} %% a bit more text per line

\begin{document}

<<setup, include=FALSE, cache=FALSE>>=
## These two settings control text width in codefig vs. usual code blocks
partWidth <- 45
fullWidth <- 80
options(width = fullWidth)

##  (1) CHUNK HOOK FUNCTION
##   First, to set R's textual output width on a per-chunk basis, we
## need to define a hook function which temporarily resets global R's
## option() settings, just for the current chunk
knit_hooks$set(r.opts=local({
    ropts <- NA
    function(before, options, envir) {
        if (before) {
            ropts <<- options(options$r.opts)
        } else {
            options(ropts)
        }
    }
}))

## (2) OUTPUT HOOK FUNCTION

##   Define a custom output hook function. This function processes _all_
## evaluated chunks, but will return the same output as the usual one,
## UNLESS a 'codefig' argument appeared in the chunk's header.  In that
## case, wrap the usual textual output in LaTeX code placing it in a
## narrower adjustbox environment and setting the graphics that it
## produced in another box beside it.

defaultChunkHook <- environment(knit_hooks[["get"]])$defaults$chunk

codefigChunkHook <- function (x, options) {
        main <- defaultChunkHook(x, options)
        before <-
            "\\vspace{1em}\n
             \\adjustbox{valign=t}{\n
             \\begin{minipage}{.59\\linewidth}\n"
        after <-
            paste("\\end{minipage}}
                   \\hfill
                   \\adjustbox{valign=t}{",
                   paste0("\\includegraphics[width=.4\\linewidth]{figure/",
                           options[["label"]], "-1.pdf}}"), sep="\n")
    ## Was a codefig option supplied in chunk header?
    ## If so, wrap code block and graphical output with needed LaTeX code.
    if (!is.null(options$codefig)) {
      return(sprintf("%s %s %s", before, main, after))
    } else {
      return(main)
    }
}

knit_hooks[["set"]](chunk = codefigChunkHook)


## (3) TEMPLATE
##   codefig=TRUE is just one of several options needed for the
## side-by-side code block and a figure to come out right. Rather
## than typing out each of them in every single chunk header, we
## define a _template_ which bundles them all together. Then we can
## set all of those options simply by typing opts.label="codefig".

opts_template[["set"]](
codefig = list(codefig=TRUE, fig.show = "hide",
               r.opts = list(width=partWidth),
               tidy = TRUE,
               tidy.opts = list(width.cutoff = partWidth)))
@

A chunk without \texttt{opts.label="codefig"} set...
<<A>>=
1:60
@

\texttt{opts.label="codefig"} \emph{is} set for this one

<<B, opts.label="codefig", fig.width=8, cache=FALSE>>=
library(raster)
library(RColorBrewer)

## Create a factor raster with a nice RAT (Rast. Attr. Table)
r <- raster(matrix(sample(1:10, 100, replace=TRUE), ncol=10, nrow=10))
r <- as.factor(r)
rat <- levels(r)[[1]]
rat[["landcover"]] <- as.character(1:10)
levels(r) <- rat

## To get a nice grid...
p <- as(r, "SpatialPolygonsDataFrame")

## Plot it
plot(r, col = brewer.pal("Set3", n=10),
     legend = FALSE, axes = FALSE, box = FALSE)
plot(p, add = TRUE)
text(p, label =  getValues(r))
@

\texttt{opts.label="codefig"} not set, and all settings back to ``normal''.
<<C>>=
lm(mpg ~ cyl + disp + hp + wt + gear, data=mtcars)
@


\end{document}
\documentclass{article}
\使用Package{adjustbox}%%对齐迷你页的顶部
\使用package[margin=1in]{geometry}%%每行多一点文本
\开始{document}
=
##这两个设置控制codefig中的文本宽度与普通代码块中的文本宽度

partWidth该演示文稿很可能是使用
\columns{}
环境与beamer组合而成的。您是在LaTeX中使用beamer还是通过另一个引擎(纯LaTeX等)进行渲染?GavinSimpson正确,在标准LaTeX文档中,我会使用
minipage
instead@baptiste我想你可以用上面的链接来回答这个问题。我现在只看到了这些回答。。。谢谢易慧有没有机会内置此功能?我能用钩子实现这个吗?我明白了,因为我知道所有的东西都是作为一个钩子来实现的,即使是内置的特性:)我支持这种方法。老实说,花了你足够长的时间:-)+1