forked from yihui/knitr-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
019-fig-caption.Rnw
41 lines (29 loc) · 1.27 KB
/
019-fig-caption.Rnw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
\documentclass{article}
\begin{document}
Knitr can automatically generate a figure environment if fig.cap is specified.
<<test, fig.cap=paste('$2 \\times 2$ is', 2*2), fig.height=2.5>>=
par(mar=c(4, 4, .1, .1)); plot(runif(4))
@
When fig.cap needs to use objects in the current chunk, we need to set the eval.after options so the objects are available when fig.cap is used.
<<setup>>=
library(knitr)
# evaluate fig.cap after a chunk is evaluated
opts_knit$set(eval.after = 'fig.cap')
@
Dynamically generate a figure caption:
<<t-test, fig.cap=paste('The P-value is', format.pval(t.test(x)$p.value)), fig.height=2.5>>=
x = rnorm(30)
par(mar=c(4, 4, .1, .1)); hist(x, main='')
@
Change the figure environment:
<<figure-asterisk, fig.env='figure*', fig.cap='Figure * environment.', fig.width=2, fig.height=4>>=
par(mar=c(4, 4, .1, .1)); boxplot(x)
@
If you have two figures, you can assign two captions to fig.cap:
<<two-caps, fig.cap=c('Hi figure one', 'Hi figure two'), fig.width=2, fig.height=1.5, fig.align='center'>>=
par(mar=rep(0, 4), ann=FALSE)
plot(1:10)
plot(runif(10))
@
You can use figure references too. For example, Figure \ref{fig:t-test} is a histogram, and Figure \ref{fig:figure-asterisk} is a boxplot. The reference key is ``fig: + the chunk label'' by default.
\end{document}