Search code examples
rlatexr-markdownpandoc

How to change code output background colour when knitting rmarkdown to pdf?


I'm preparing a pdf document with rmarkdown. I'd like to know whether there is a way to change the code output's background color, so that the output is more distinguishable from other texts.

My current solution only changes the color of the code chunk itself. Thanks!

---
title: "Untitled"
output: 
  pdf_document:
    highlight: default
header-includes: \usepackage{xcolor}
---

\definecolor{shadecolor}{RGB}{225, 225, 225}

Plain text.

```{r}
a <- c(1,2,3,4,5)
b <- c(1,2,3,4,5)
df <- data.frame(a, b)

# take a look at our data frame
df
```

Plain text.

Solution

  • A nice trick is to pass a class name to class.output, and then shadecolor will also be applied on chunk output too.

    I have used "shadebox" as a class name but it can be any valid string.

    ---
    title: "Untitled"
    output: 
      pdf_document:
        highlight: default
    header-includes: \usepackage{xcolor}
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE, class.output="shadebox")
    ```
    
    \definecolor{shadecolor}{RGB}{225, 225, 225}
    
    Plain text.
    
    ```{r}
    a <- c(1,2,3,4,5)
    b <- c(1,2,3,4,5)
    df <- data.frame(a, b)
    
    # take a look at our data frame
    df
    ```
    
    Plain text
    

    gray shaded bg color for chunk output