knitr - 如何对齐代码和并排绘图

Ren*_*aud 10 r knitr

是否有一种简单的方法(例如,通过块选项)来获取块的源代码和它并排生成的图,如本文档的第8页(以及其他)?

我试过使用out.width="0.5\\textwidth", fig.align='right',这使得绘图正确占据了页面的一半并且与右边对齐,但源代码显示在它上面,这是正常的行为.我想把它放在情节的左侧.

谢谢

示例代码:

<<someplot, out.width="0.5\\textwidth", fig.align='right'>>=
plot(1:10)
@
Run Code Online (Sandbox Code Playgroud)

Jos*_*ien 8

好吧,这最终比我想象的更棘手.

在乳胶方面,adjustbox让您的并排侧框对齐很大的控制,很好地证明了在这个优秀的答案上tex.stackexchange.com了.因此,我的总体策略是包裹格式,整理,彩色与LaTeX的代码所示[R块的输出:(1)其放在一个adjustbox环境内; (2)将块的图形输出包含在右侧的另一个调整框环境中.为了实现这一点,我需要将knitr的默认块输出钩子替换(2)为在文档<<setup>>=块的部分中定义的自定义块输出钩子.

部分(1)<<setup>>=定义了可以用于暂时设置任何讨论R的全局选项(并且特别是在这里,块钩options("width")在每块的基础上).请看这里的问题和答案,只处理这个设置的一部分.

最后,Section (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}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


小智 2

您可以在 PerformanceAnalytics 包或 gplots 中的“textplot”中显示文本。

(小)缺点:据我所知,无法进行语法突出显示。

示例代码:

```{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)
```
Run Code Online (Sandbox Code Playgroud)