7

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?

imouellette81
  • 234
  • 2
  • 5
  • This - http://stackoverflow.com/questions/16626462/figure-position-in-markdown-when-converting-to-pdf-with-knitr-and-pandoc - might have a bit of what you're looking for, but I think you're still stuck in latex manipulation land for the heavy lifting. – hrbrmstr Mar 12 '14 at 10:51
  • @hrbrmstr yea I've taken a look at that example and many others. I ended up using latex manipulation rather than knitr arguments. From now on I think I'll use latex for any overlapping knitr arguments. – imouellette81 Mar 18 '14 at 17:07

1 Answers1

7

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 = '')
})
```
jessi
  • 1,438
  • 1
  • 23
  • 36
  • 1
    Nice! See also http://stackoverflow.com/questions/24657216/caption-above-figure-using-knitr in case you are interested in LaTeX output instead. – Matifou Nov 11 '14 at 22:01