Last active
August 3, 2022 09:37
-
-
Save emilyriederer/d98c78d80c3eb3b1f9a3a499736e2229 to your computer and use it in GitHub Desktop.
Generate <style> block of CSS to change tabset colors by a condition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
title: "Untitled" | |
author: "Emily Riederer" | |
date: "5/15/2019" | |
output: html_document | |
--- | |
```{r} | |
# dummy data | |
data <- data.frame( | |
METRIC = paste('var', 1:10), | |
VAL = runif(10), | |
stringsAsFactors = FALSE | |
) | |
``` | |
```{r results = 'asis'} | |
# automatically generate <style> block of css for each tab | |
tab_number <- 1:nrow(data) | |
tab_color <- ifelse(data$VAL > 0.75, 'green', ifelse(data$VAL > 0.25, 'yellow', 'red')) | |
css <- sprintf(".color-tabs>.nav-pills>li:nth-child(%d){background:%s;}", tab_number, tab_color) | |
css <- paste(css, collapse = "\n") | |
css <- paste("<style>", css, "</style>") | |
cat(css) | |
``` | |
# section {.color-tabs .tabset .tabset-pills} | |
```{r, results='asis'} | |
# dynamically generate code for each chunk | |
vars <- data$METRIC | |
val <- data$VAL | |
out <- paste("##", vars, "<br>\n", "The value is ", val, "<br>\n<br>\n\n") | |
invisible(lapply(out, cat)) | |
``` | |
# section 2 {.color-tabs .tabset .tabset-pills} | |
```{r} | |
# create plots | |
library(ggplot2) | |
plots <- | |
lapply(1:10, | |
function(x) ggplot(data[data$METRIC == paste("var", x),], aes(x = 1, y = VAL)) + geom_col() | |
) | |
``` | |
```{r echo = FALSE, results ='asis'} | |
invisible( | |
mapply( | |
function(name, plot) { | |
cat('\n##', name, '\n') | |
print(plot) | |
cat('\n') | |
}, | |
name = data$METRIC, | |
plot = plots | |
) | |
) | |
``` | |
# section 3 {.tabset .tabset-pills} | |
This verifies that CSS does not "bleed" into non-colored sections | |
## tab 1 | |
content | |
## tab 2 | |
content |
Hello, Thank you.
I would like to ask you, I am using your code for multiple tabset chunks with different ccs styles (every chunk has various data$VAL) . However Rmarkdown uses only the last one ccs style.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nicely done