Changing chunk background color in RMarkdown

不羁岁月 提交于 2019-12-17 23:30:08

问题


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 chunk option background = 'red' and get what I want, but this does not seem to work in .Rmd. My guess is that I need to make a custom css stylesheet (though what the selector would be, I don't know), and maybe also create a custom hook. I'd like it to be on a per-chunk basis, not an overall change for the entire document.


回答1:


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)
```



回答2:


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)
```




回答3:


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)
```



来源:https://stackoverflow.com/questions/41030477/changing-chunk-background-color-in-rmarkdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!