Custom CSS to rmarkdown chunk to change width of graph - css

I have an rmarkdown document which output html. I have my own css styles that I use by adding it to the YAML header. I also want to control css of specific code chunks. I have a dashboard (3x2 grid of plots) that I want to have larger width than the main document.
I've found these two questions:
Add a CSS class to single code chunks in RMarkdown
Adding custom CSS tags to an RMarkdown html document
But neither of them are working for me (or I didn't understand the answers). I want to change the width of a plot so it float into the margins e.g. width: 110%. I tried this:
```{r dash1, fig.height=16, fig.width=14, results="asis"}
cat("
<style>
.toc-content {
width: 110%;
}
</style>
")
margin = theme(plot.margin = unit(c(1,2,1,2), "cm"))
pl_1 <- list(g_1_kaupmattur, g_2_gallup, g_3_vnv, g_4_spa, g_5_ibud, g_6_swirlo)
grid.arrange(grobs = lapply(pl_1, "+", margin), ncol = 2)
```
This changed the whole document, not only the output of this particular chunk.
I also tried creating a new css style with width: 110% and adding it to the chunk option like this:
```{r dash1, fig.height=16, fig.width=14, class.source="dash_styles"}
margin = theme(plot.margin = unit(c(1,2,1,2), "cm"))
pl_1 <- list(g_1_kaupmattur, g_2_gallup, g_3_vnv, g_4_spa, g_5_ibud, g_6_swirlo)
grid.arrange(grobs = lapply(pl_1, "+", margin), ncol = 2)
```
It didn't work either.
I would like the plot to extend to the margins as I "show" on the screenshot below.

Related

CSS selector for font color in flextable with shadow host on

I'm unsuccessfully trying to set the font color for flextable generated in r markdown using a css stylesheet.
I can accomplish this when I turn off shadow host, but not with it on. (Just turning it off removes other desirable features.) Here's a short r markdown file demonstrating the difference.
---
title: "Untitled"
output: html_document
---
<style>
div.flextable-shadow-host * {
color: pink;
}
div.tabwid * {
color: pink;
}
</style>
# ignores CSS above
```{r, echo=FALSE}
library(flextable)
flextable(head(mtcars))
```
# accepts CSS above
```{r, echo=FALSE}
ft <- flextable(head(mtcars))
htmltools_value(ft, ft.shadow = FALSE)
```
I want the css external to the r code because I have a button selector on the website the user can change the overall style (e.g., dark mode or not).
When using shadow, the table is assembled outside of HTML. Only the id connects the table to HTML. However, flextable has functions for setting the color. Why not just use one of the many built-in methods to change the color?
For example:
# ignores CSS above
```{r liberator,include=F}
library(flextable)
library(tidyverse)
```
```{r tbler, echo=FALSE}
flextable(head(mtcars)) %>%
color(color = "pink", part = "all")
```
# accepts CSS above
```{r, echo=FALSE}
ft <- flextable(head(mtcars))
htmltools_value(ft, ft.shadow = FALSE)
```
There are many things you can do with flextable styling. You can see more customization options here.
Update: Based on your comments
Okay, this works to change the color of a flextable.
This works if there is only one flextable in the script.
I have the color of the text set to #b21E29 (a shade of red). You can change that as you see fit.
These will SKIP non-shadow flextables
Add this chunk anywhere in your RMD script. This requires no additional libraries or any other customization in your R code.
```{r js_ing,results="asis",engine="js",echo=F}
// extract the styles that are set for the flextable
letMe = document.querySelector('div.flextable-shadow-host').shadowRoot.querySelector('div>style');
// replace color style
// preceding ';' so that 'background-color' doesn't change
letMe.innerHTML = letMe.innerHTML.replace(/;(color:.+?);/g, ';color:#b21e29 !important;');
```
If you have more than one flextable with shadow on, you can use one of the two following chunks instead. In the first--all the same color; in the second--each table has a different color.
These work if there is more than one flextable in the script.
Pay attention to the comments so you can see what to use when depending on your desired output.
All the same color:
```{r moreJs_ing,results="asis",engine="js",echo=F}
// collect all of the flextables with shadow
letMe = document.querySelectorAll('div.flextable-shadow-host');
// to set all shadow flextables to the same font color:
for(i = 0, n = letMe.length; i < n; i++){
showMe = letMe[i].shadowRoot.querySelector('div>style');
showMe.innerHTML = showMe.innerHTML.replace(/;(color:.+?);/g, ';color:#b21e29 !important;');
}
```
Each with there own color:
```{r evenMoreJs_ing,results="asis",engine="js",echo=F}
//alternatively to set each to a different color
// make sure you only include one of these options!
// collect all of the flextables with shadow
letMe = document.querySelectorAll('div.flextable-shadow-host');
// first table in script
showFirst = letMe[0].shadowRoot.querySelector('div>style');
showFirst.innerHTML = showFirst.innerHTML.replace(/;(color:.+?);/g, ';color:#b21e29 !important;');
// second table in script
showSecond = letMe[1].shadowRoot.querySelector('div>style');
showSecond.innerHTML = showSecond.innerHTML.replace(/;(color:.+?);/g, ';color:#003b70 !important;');
// change the indices for each table, keep in mind the first table is [0], not [1]
```
If you aren't sure where you want to go with these, add all three and and include=F as a chunk option to the two you aren't using at that moment in time.

Make graphics the same size (width & height) when side by side in Rmarkdown html document

I know how to put a number of plots side by side within a html output using Rmarkdown
{r maps, fig.cap = "Fig. Z - Maps", fig.show="hold", out.width="25%", fig.align = "center", echo = FALSE}
knitr::include_graphics("plots/X1.map.png")
knitr::include_graphics("plots/X2.map.png")
knitr::include_graphics("plots/X3.map.png")
knitr::include_graphics("plots/X4.map.png")
Each of these maps have been created and saved using tmap function, saving each map with the same height and width:
tmap_save(X1.map, "plots/X1.map.png", height = 4, width = 1.5)
However, when knitting the html document together the maps, although having the same widths have different heights.
Any help would be much appreciated.
Have you tried setting the size of your plots in your global chunk options? This is probably not going to work if you don't have the code to those plots instead of the saved png's.
knitr::opts_chunk$set(fig.width=x, fig.height=y)
Alternatively if you only have access to the png's you can try this:
knitr::include_graphics("plots/X1.map.png"){ width=z% }
knitr::include_graphics("plots/X2.map.png"){ width=z% }
knitr::include_graphics("plots/X3.map.png"){ width=z% }
knitr::include_graphics("plots/X4.map.png"){ width=z% }
Replace the x, y, and z with the values you'd like.

Compact table in html document rmarkdown with kableExtra?

I'm trying to make a 'compact' table in an RMarkdown
I've tried a few things, mostly variations on setting a custom css class and providing the custom css class to a code chunk
I've tried a lot of variations, all of which I can see flow through to the source code (accessed via knitting the html document, opening in chrome, and cmd + opt + u to view source and inspecting the source)
However, I can't work out what's necessary to simply make rows thinner (I believe that's simply reducing cell padding) in a kableExtra table
What I've tried so far
Here's one variation of what I've tried, but the rows are not compact as hoped (they are the standard height)
Which is done with:
---
output: html_document
---
```{r setup, include=FALSE}
library(dplyr); library(kableExtra)
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE)
library(dplyr)
library(kableExtra)
```
<style>
pre code, pre, code {
padding: 200 !important;
}
</style>
```{r}
iris %>%
kable %>%
kable_styling("striped", full_width = F) %>%
column_spec(4:5, bold = T) %>%
row_spec(3:5, bold = T, color = "white", background = "#D7261E")
```
but note that the custom css is not taking effect
The easiest way is to override the Bootstrap CSS, decreasing value of padding property (default value is 8px):
<style>
.table>tbody>tr>td{
padding: 1px;
}
</style>
As you pointed out, inspecting the source will lead you to the values above:
You could also do something similar within row_spec(1:nrow(iris), extra_css = "..")
To make the kable rows smaller in a knit to HTML, you can use bootstrap_options = c("condensed") in your kable_styling:
kable_styling(bootstrap_options = c("condensed"))
See https://cran.r-project.org/web/packages/kableExtra/vignettes/awesome_table_in_html.html
If anyone knows the pdf variant for it, please let me know :)

Height of RMarkdown code chunk in reveal.js slides

I keep running into the problem of my code chunks overflowing in my slides, and so having to scroll around them. Not optimal for teaching.
How can one make a code chunk taller (or wider) on a chunk by chunk basis?
How can one in reveal.js or other html formats change code text size, again, on a chunk by chunk basis. I know globally I can change things in the CSS, but want to be more dynamic than that.
p.s. If anyone wants to know how to change the center-text behavior while not affecting other slide elements, troubleshot that one recently, and it's nontrivial, but doable.
Customize Code Chunks using CSS
You could use fenced_code_attributes to add a CSS class (or several different classes) to certain code chunks. For this to work, you add this option to your YAML header and define a new hook using knit_hoooks$set() (for details see Hooks). After that, we can use the chunk option class = 'myCssClass'.
In the following example we define a class .smallCode, which sets a certain width for the chunk and a smaller font size. In the final document, the result looks like this:
<pre class="sourceCode r smallCode">
<code class="sourceCode r">
THE CODE WE PRODUCED
</code>
</pre>
As you can see, we just added the class smallCode to the <pre> element! Yay!
You can modify anything, the font styles, the background and much more. For an overview of possibilities check out this CSS Tutorial
Wrapping Source Code
If you want the source code to be wrapped, you can use the chunk option tidy=T with its option width.cutoff (also implemented in the example below).
Reproducible Example:
---
title: "Customized Code Chunks"
author: Martin Schmelzer
date: March 22, 2005
output:
revealjs::revealjs_presentation:
md_extensions: +fenced_code_attributes
---
<style>
pre.smallCode {
width: 360px; /* Change the width of the chunk */
height: 360px; /* Change the height of the chunk */
font-size: 0.4em; /* Change the font-size */
background-color: lightgrey; /* Change background color */
}
</style>
```{r, include=FALSE}
knitr::knit_hooks$set(source = function(x, options) {
return(paste0(
"```{.r",
ifelse(is.null(options$class),
"",
paste0(" .", gsub(" ", " .", options$class))
),
"}\n",
x,
"\n```"
))
})
```
# Customized Code Chunks
## Example
<!-- Here we use the option tidy=TRUE with a cutoff after 40 characters -->
```{r, class = 'smallCode', tidy=T, tidy.opts=list(width.cutoff=40)}
df <- data.frame(A = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20))
```
And here is a screenshot of the code chunk we just have customized:

Wrapping plots in another html container within an Rmd file

I have a situation where, for display purposes, I need to wrap an outputted plot in a <div> container.
At the most basic level, this is what I would like to do:
```{r fig.width=7, fig.height=6,results='asis',echo=FALSE}
cat('<div>')
plot(cars)
cat('</div>')
```
However, the output document looks like this:
![plot of chunk unnamed-chunk-2](figure/unnamed-chunk-2.png)
Is there a workaround if you need to "wrap" output?
The same behaviour only seems to occur when it's wrapping the plot. Otherwise, including closed tags works as expected:
```{r fig.width=7, fig.height=6,results='asis',echo=FALSE}
cat('<div>')
cat('</div>')
plot(cars)
cat('<h1>Hello</h1>')
```
Yet wrapping the image seems to break it. I'm also noticing that <img> is wrapped in <p> is it possible to stop this behaviour?
Here is one way to do it.
First, we create a chunk hook to wrap chunk output inside a tag.
We pass wrap = div as chunk option to wrap inside div.
Set out.extra = "" to fool knitr into outputting html for plot output. Note that this is required only for div tag and not for span, as markdown is parsed inside span tag.s
DONE!
Here is a gist with Rmd, md and html files, and here is the html preview
## knitr Chunk Hook to Wrap
```{r setup, echo = F}
knit_hooks$set(wrap = function(before, options, envir){
if (before){
paste0('<', options$wrap, '>')
} else {
paste0('</', options$wrap, '>')
}
})
```
```{r comment = NA, echo = F, wrap = 'div', out.extra=""}
plot(mtcars$mpg, mtcars$wt)
```

Resources