与绘图相比,针对ggplot的knitr hook的不同(错误)行为

时间:2018-05-08 14:19:13

标签: r ggplot2 knitr

我尝试在循环中创建一堆图形,并希望通过using this hook添加上面的标题。 是否可以修改此钩子,以便可以提交长度为>的向量。 1到capT并获得与fig.cap相同的结果,但上面有标题? 本文档以错误结束!

预期结果将是: 带有第一个标题的第一个图形,带有第二个标题的第二个图形等。

\documentclass{article}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\begin{document}

<<init, echo=FALSE, results='hide'>>=
library(knitr)
knitr::opts_chunk$set(echo=FALSE, 
                      results='hide', 
                      warning=FALSE, 
                      message=FALSE,
                      error = FALSE)

f <- function(x, options) {
  paste("\\end{kframe}\n", 
        "\\caption{", options$capT, "}\n",
        #"\\begin{figure}",
        hook_plot_tex(x, options), 
        #"\\end{figure}",
        "\n\\begin{kframe}", sep = "")
}
knitr::knit_hooks$set(plot = f)
@

Some Text.

<<first, capT=c('one', 'two', 'three')>>=
for(i in 1:3)
{
plot(1:10,1:10)
}
@

\end{document}

更新

现在正在运作。这很容易解决。但现在我遇到ggplot2的问题。

\documentclass{article}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\begin{document}

<<init, echo=FALSE, results='hide'>>=
library(knitr)
knitr::opts_chunk$set(echo=FALSE, 
                      results='hide', 
                      warning=FALSE, 
                      message=FALSE,
                      error = FALSE)

f <- function(x, options) {
  paste("\\end{kframe}\n", 
        "\\begin{figure}",
        "\\caption{", options$capT, "}\n",
        hook_plot_tex(x, options), 
        "\\end{figure}",
        "\n\\begin{kframe}", sep = "")
}
knitr::knit_hooks$set(plot = f)
@

Some Text.

<<first, capT=c('one', 'two', 'three')>>=
for(i in 1:3)
  {
  plot(1:10, 1:10)  
  }
@

\end{document}

使用plot()导致:

caption1 - plot1; caption2 - plot2; caption3 - plot3; (预期产出)

ggplot()导致:

caption1 - plot1; caption1 - plot2; caption1 - plot3; caption2 - plot1等。

\documentclass{article}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\begin{document}

<<init, echo=FALSE, results='hide'>>=
library(knitr)
knitr::opts_chunk$set(echo=FALSE, 
                      results='hide', 
                      warning=FALSE, 
                      message=FALSE,
                      error = FALSE)

f <- function(x, options) {
  paste("\\end{kframe}\n", 
        "\\begin{figure}",
        "\\caption{", options$capT, "}\n",
        hook_plot_tex(x, options), 
        "\\end{figure}",
        "\n\\begin{kframe}", sep = "")
}
knitr::knit_hooks$set(plot = f)
@

Some Text.

<<first, capT=c('one', 'two', 'three')>>=
library(ggplot2)

for(i in 1:3)
  {
  d <- data.frame(a=1:10,b=1:10)
  p = ggplot(d, aes(a,b)) + geom_point()
  print(p)
  }
@

\end{document}

为什么ggplot2的输出表现不同?

谢谢!

0 个答案:

没有答案