Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knitr - Figure captions above

Tags:

r

latex

knitr

Is there a way, in knitr to move the fig.cap above the figure? I need them above so that when the list-of-figure's hyperlink is selected for a certain table it navigates to the figure. Right now the caption and thus hyperlink target are at the bottom so when selected only the caption is shown at the top of the page and one must scroll up to see the figure...rather silly.

Example of my current code:

<<Race, fig.lp='fig:', fig=TRUE, eval=TRUE, echo=FALSE, dev='png', fig.pos='H', fig.width=8, fig.height=4, fig.cap='Race', fig.align='center', dpi=300>>=
b <- ggplot(melt(race.plot, id=c("Type"), variable.name="Race", value.name="Count"))
b + geom_bar(aes(Race, y=Count, fill=Race), position="dodge", stat="identity", alpha=0.7) + 
  ggtitle("Race") + xlab("") + ylab("Count") +
  facet_wrap(~Type, nrow=2, scale="free_y") +
  theme(plot.title=element_text(size=25), 
    axis.title=element_text(size=15), 
    axis.text.y=element_text(size=10),
    axis.text.x=element_blank(),
    axis.ticks.x=element_blank())
@

I understand there are ways to do so using latex and leaving fig.cap alone in the knitr chunk:

\begin{figure} 
\caption{This is a caption above the figure} 
<<a-plot, echo=FALSE>>= 
plot(1) 
@ 
\end{figure} 

Most suggestions are to do the above, but date around 2012 or early 2013. Am wondering if any changes to knitr allow this functionality now.

I've been using the options in knitr and xtable to control most things in my output but what is the consensus? Should I avoid this and use latex options outside knitr chunks whenever possible?

like image 791
imouellette81 Avatar asked Mar 11 '14 20:03

imouellette81


1 Answers

Maybe too late, but I think Yihui answered this.

You can change the knit hook for all figures to have the caption above the figure. For example, here is a version of a chunk from an .Rmd document. If you tell knitr to change the option for figure to have the document look first at and then at the actual .

```{r setup}
library(knitr)
knit_hooks$set(plot = function(x, options) {
  paste('<figure><figcaption>', options$fig.cap, '</figcaption><img src="',
        opts_knit$get('base.url'), paste(x, collapse = '.'),
        '"></figure>',
        sep = '')
})
```
like image 133
jessi Avatar answered Sep 28 '22 07:09

jessi