2

我创建了一个 for 循环,它使用tikzDevice包将 R 中的多个图(通过 ggplot2)输出到单个 .tex 文件中。这使得使用指向从 R 输出的 .tex 文件的单个命令(例如“diagrams.tex”)更容易在乳胶文档中包含多个图表\include{diagrams}

但是,我还想将每个 tikzpicture 与\begin{figure}环境包装起来,这样我就可以在每个相应的图中插入两行额外的行:\caption{}\label{}.

问题:有没有办法在输出的 .tex 文件中为每个相应的 ggplot 图像(来自我的 R 循环)直接包含图形包装器、标题和标签乳胶命令?

这是可重现的 R 代码,它生成包含 3 个 ggplot 的文件“diagrams.tex”:

require(ggplot2)
require(tikzDevice)

## Load example data frame
A1 = as.data.frame(rbind(c(4.0,1.5,6.1),
c(4.0,5.2,3.5),
c(4.0,3.4,4.3),
c(4.0,8.2,7.3),
c(4.0,2.9,6.3),
c(6.0,3.9,6.6),
c(6.0,1.5,6.1),
c(6.0,2.7,5.3),
c(6.0,2.9,7.4),
c(6.0,3.7,6.0),
c(8.0,3.9,4.2),
c(8.0,4.1,3.5),
c(8.0,3.7,5.8),
c(8.0,2.5,7.5),
c(8.0,4.1,3.5)))
names(A1) = c("state","rmaxpay","urate")

i = 2

## name output file
tikz( 'diagrams.tex' )

for (i in 2:4){     #begin LOOP

st = i*2

df = NULL
df = subset(A1, state == st , select = c(2:3))

print(              # start print

ggplot(df, aes(rmaxpay,urate)) + geom_point() 

  )                 # end print

  }         #end LOOP

dev.off()
4

1 回答 1

3

可能有一种方法可以使用绘图钩子来做到这一点,但你可以使用console选项和来做到这一点sink()

require(ggplot2)
require(tikzDevice)

## Load example data frame
A1 = as.data.frame(rbind(c(4.0,1.5,6.1),
c(4.0,5.2,3.5),
c(4.0,3.4,4.3),
c(4.0,8.2,7.3),
c(4.0,2.9,6.3),
c(6.0,3.9,6.6),
c(6.0,1.5,6.1),
c(6.0,2.7,5.3),
c(6.0,2.9,7.4),
c(6.0,3.7,6.0),
c(8.0,3.9,4.2),
c(8.0,4.1,3.5),
c(8.0,3.7,5.8),
c(8.0,2.5,7.5),
c(8.0,4.1,3.5)))
names(A1) = c("state","rmaxpay","urate")

i = 2
fn <- "diagrams.tex"
if(file.exists(fn)) file.remove(fn)

for (i in 2:4){     #begin LOOP

  st = i*2

  df = NULL
  df = subset(A1, state == st , select = c(2:3))

  cat("\\begin{figure}\n", file = fn, append=TRUE)
  sink(fn, append=TRUE)
  tikz(console = TRUE)
    print(              # start print
      ggplot(df, aes(rmaxpay,urate)) + geom_point() 
    )                 # end print
  dev.off()
  sink()
  cat(paste("\\caption{figure}\\label{fig:",i,"}\n",sep=""), file = fn, append=TRUE)
  cat("\\end{figure}\n", file = fn, append=TRUE)

}         #end LOOP
于 2011-06-23T16:45:09.903 回答