Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

r - knitr - Figure captions above

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:

egin{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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 = '')
})
```

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...