TikZDevice:使用 R 将 \caption{} 和 \label{} 添加到 TikZ 图
我创建了一个 for 循环,使用 tikzDevice
包将 R 中的多个绘图(通过 ggplot2)输出到单个 .tex 文件中。这样可以更轻松地使用指向 R 输出的 .tex 文件(例如“diagrams.tex”)的单个命令在 Latex 文档中包含多个图表:\include{diagrams}
。
但是,我还想使用 \begin{figure}
环境包装每个 tikzpicture,以便我可以在每个相应的图形中插入另外两行: \caption{}
和 \label{}
。
问题:有没有办法在输出的 .tex 文件中直接包含每个各自的 ggplot 图像(来自我的 R 循环)的图形包装器、标题和标签 Latex 命令?
下面是可重现的 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()
I've created a for loop that outputs several plots (via ggplot2) from R into a single .tex file using the tikzDevice
package. This makes it easier to include multiple diagrams from within a latex document using a single command that points to the .tex file outputted from R (say 'diagrams.tex'): \include{diagrams}
.
However, I would also like to wrap each tikzpicture with the \begin{figure}
environment, so that I can insert two additional lines into each respective figure: \caption{}
and \label{}
.
Question: is there a way to include the figure wrapper, caption, and label latex commands directly, for each respective ggplot image (from my R loop), in the outputted .tex file?
Here is reproducible R code that generates a file 'diagrams.tex' containing 3 ggplots:
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可能有一种方法可以使用绘图钩子来完成此操作,但实际上您可以使用
console
选项和sink()
来完成此操作:There may be a way to do this with plot hooks but as it is you can do it by using the
console
option andsink()
: