Search code examples
rlatexr-markdown

How can I use different colours for in-text citations and figure hyper-references in RMarkdown?


Consider the following RMarkdown document:

---
output: 
  pdf_document:
    number_sections: true
    fig_caption: yes
title: 'Title'
author: 
  - Name
geometry: margin=1in
bibliography: references.bib
csl: something.csl
link-citations: yes
linkcolor: blue
urlcolor: black

header-includes:
 \usepackage{setspace}
 \usepackage{graphicx}
 \usepackage[colorlinks]{hyperref}
 \usepackage[all]{hypcap}
---

Lorem ipsum [@reference]

```{r landscape, echo=FALSE,include=TRUE,warning=FALSE,fig.cap="\\label{fig:landscape}Caption"}

knitr::include_graphics("file.png")

```

Referencing to \autoref{fig:landscape}.

When I run this sort of document, I see the same hyper-linked colour (blue) for both citations (like the [@reference] and references to the figure (the \autoref).

enter image description here

enter image description here

I want to be able to separate the colouring of my references and hyperlinks to figures in the same document (like blue for the Evanno et al., 2005 in the image and red for the Figure 2). How can I do this in RMarkdown? I've tried wrapping the \autoref{} in a \color{red}{\autoref{fig:landscape}} but this did not work.


Solution

  • We can follow the technique described here to define a new command for figure referencing.

    ---
    title: 'Title'
    output: 
      pdf_document:
        number_sections: true
        fig_caption: yes
    author: 
      - Name
    geometry: margin=1in
    bibliography: reference.bib
    link-citations: yes
    linkcolor: blue
    urlcolor: black
    header-includes:
      \newcommand\figref[1]{{\hypersetup{linkcolor=red}\autoref{#1}}}
    ---
    
    Lorem ipsum [@R-base]
    
    ```{r landscape, echo=FALSE,include=TRUE,warning=FALSE,fig.cap="\\label{fig:landscape}Caption"}
    
    plot(1:10)
    
    ```
    
    Referencing to \figref{fig:landscape}.
    
    

    different color for figure reference