dyn*_*amo 22 latex r subfigure knitr
是否有可能使用knitr生成子图(带有相关的子标题)?这是一个最小的工作示例:
\documentclass{article}
\begin{document}
<<echo = FALSE, fig.cap = c("Some numbers.", "Some more numbers."), out.width = "0.5\\textwidth", fig.align = "center">>=
plot(1:10)
plot(30:100)
@
\end{document}
Run Code Online (Sandbox Code Playgroud)
这导致标记为图1和图2的两个图,其中标题(分别)被定义.但是我希望它们被标记为"图1a"和"图1b",就像使用子标题LaTeX包一样.
我知道有一个knitr选项"fig.env",但这并没有解决它(至少没有使用,例如,"fig.env ='subfigure'").这里有关于Sweave的类似帖子,但解决方案是一个不优雅的黑客:http://texblog.org/2011/12/01/sweave-subfig-controlling-figure-size-and-placement/
Yih*_*Xie 34
knitr(> = v1.5)支持子图.您可以使用chunk选项fig.subcap.这是一个最小的例子.
\documentclass{article}
\usepackage{subfig}
\begin{document}
<<fig-sub, fig.cap='two plots', fig.subcap=c('one plot', 'the other one'), out.width='.49\\linewidth'>>=
plot(1:10)
plot(rnorm(10), pch=19)
@
\end{document}
Run Code Online (Sandbox Code Playgroud)

您可以使用Latex的子标题包.
\documentclass{article}
\usepackage{subcaption}
\begin{document}
\begin{figure}
\centering
\begin{subfigure}[b]{0.3\textwidth}
\centering
<<echo = FALSE, out.width = "0.5\\textwidth", fig.align = "center">>=
plot(1:10)
@
\caption{text for first figure}
\label{fig:gull}
\end{subfigure}%
\begin{subfigure}[b]{0.3\textwidth}
\centering
<<echo = FALSE, out.width = "0.5\\textwidth", fig.align = "center">>=
plot(30:100)
@
\caption{text for second figure}
\label{fig:tiger}
\end{subfigure}
\caption{Figure caption}
\end{figure}
\end{document}
Run Code Online (Sandbox Code Playgroud)

更新Yihui的答案以反映Rmarkdown在过去几年中的变化以及从Rnw文件的转移。
如knitr 块选项中所列,子图需要在块头中设置一些其他设置:
fig.subcap 是子图标题的列表fig.ncol:子图的列数out.width:数字的输出宽度。通常,您将设置为100%除以子列数。子图还需要LaTeX软件包subfig。\usepackage{subfig}因此,该行必须包含在YAML中,或者,如果您使用的是外部tex模板,则可以将此行添加到该文件中。
这是一个基本模板:
---
output: pdf_document
header-includes:
- \usepackage{subfig}
---
```{r fig-sub, fig.cap='two plots', fig.subcap=c('one plot', 'the other one'), out.width='.49\\linewidth', fig.asp=1, fig.ncol = 2}
plot(1:10)
plot(rnorm(10), pch=19)
```
Run Code Online (Sandbox Code Playgroud)
如果您要绘制包含多个ggplot图的子图,可能会造成混乱,因为它们不在图之间对齐。您可能想在这里查看有关如何使用Cowplot强制ggplots具有相同尺寸的文章。
该stackoverflow帖子将帮助您确保所有图都对齐,如下图所示:
只是将其作为子图的可能扩展。我喜欢用它们来喂养他们一系列的数字。也许您已经产生了一个功能,需要在四个不同的试用组或四个单独的位置上运行。例如,以下是英国四个城市的列表:
```{r}
locations <- c("Southampton, UK", "London, UK", "Bristol, UK", "Birmingham,
```
Run Code Online (Sandbox Code Playgroud)
然后,可以在fig.sub和中使用此列表lapply以生成子图列表。如果您需要运行
```{r fig-sub-2, fig.cap='A collection of maps', fig.subcap= locations, out.width='.49\\linewidth', fig.asp=1, fig.ncol = 2}
library(ggmap)
lapply(locations, function(x)
ggmap(get_map(x))
)
```
Run Code Online (Sandbox Code Playgroud)
这使得子图非常强大。如果我需要在另外两个城市中运行模型,我所要做的就是向location列表中添加额外的值,子图的长度将相同。
| 归档时间: |
|
| 查看次数: |
6849 次 |
| 最近记录: |