Changing chunk background color in RMarkdown

后端 未结 4 1495
一整个雨季
一整个雨季 2020-12-04 21:45

I would like to have a certain code chunk highlighted in a different color (e.g. red) to indicate that it is bad practice. If I was using .Rnw, I could add the

相关标签:
4条回答
  • 2020-12-04 22:35

    This solution is a bit hack-y, but it works. The gist of it is to make two code chunks, swapping the {r} designator with a unique class name. Then add css code to style each chunk.

    ---
    output: html_document
    ---
    
    <style>
    pre.bluecars {
        background-color: #aabbff !important;
    }
    pre.redcars {
        background-color: #ffbbbb !important;
    }
    </style>
    
    ## chunk-specific bg colors
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE)
    ```
    
    - blue
    
    ```{bluecars}
    summary(cars)
    ```
    
    ```{r, echo=FALSE}
    summary(cars)
    ```
    
    - normal
    
    ```{r}
    summary(cars)
    ```
    
    - red
    
    ```{redcars}
    summary(cars)
    ```
    
    ```{r, echo=FALSE}
    summary(cars)
    ```
    

    0 讨论(0)
  • 2020-12-04 22:37

    I found the following way to color (code) chunks in Rmarkdown documents that I knit to PDF:

    Use a pandoc highlighting scheme as a basis

    pandoc --print-highlight-style pygments > my.theme
    

    Then edit my.theme by using a regex to set all

    "text-color": null
    

    Then, you can change this property to any color you like (this one here is lightgrey)

    "background-color": "#f8f8f8"
    

    In the YAML of your .Rmd document under "pdf_document", put the following

    pandoc_args: --highlight-style=my.theme
    

    For my use case this is all I need.

    0 讨论(0)
  • 2020-12-04 22:46

    Remember markdown supports HTML outside of code blocks.

    I would surround the code chunks with a div with a custom class that styled them how I wanted. This example styles the code in blue, the output in light blue

    <style>
    div.blue pre { background-color:lightblue; }
    div.blue pre.r { background-color:blue; }
    </style>
    
    <div class = "blue">
    ```{r bluecars}
    summary(cars)
    ```
    </div>
    
    ```{r normal}
    summary(cars)
    ```
    

    0 讨论(0)
  • 2020-12-04 22:48

    We can use the class.source option in the code chunk header to provide custom CSS to R Markdown. This is explained in the following post:

    Add a CSS class to single code chunks in RMarkdown

    Putting together an example, I might set a class called "badCode" then have a bit of CSS to change the background as you might like. Here's my .Rmd:

    ---
    output: html_document
    ---
    
    ```{css}
    .badCode {
    background-color: red;
    }
    ```
    
    ```{r mtcars}
    summary(mtcars)
    ```
    
    ```{r cars, class.source="badCode"}
    summary(cars)
    ```
    
    0 讨论(0)
提交回复
热议问题