Set cell width in knitr/pandoc? - html

I am generating a HTML file with knitr/pandoc which prints several tables in a loop. Here is a minimal example:
---
output:
html_document:
theme: cosmo
---
```{r results ="asis", echo=FALSE, warning=FALSE, kable}
library(knitr)
library(markdown)
library(pander)
for (i in 1:12) {
df = data.frame(matrix(rnorm(i), nrow=2))
cat(pandoc.table(df, split.table = Inf))
}
```
The printed data frames (tables) have a different number of cells, but they all have the same total width.
I tried to set a fixed width with CSS by setting the table width to "auto" and align it left, but I didn't succeed. How can I do this?

This is due to the width: 100% setting in the original CSS. You can override that by using a custom theme or an additional CSS -- e.g. something minimal like this:
table {
width: auto !important;
}
The !important rule stands for forcing this width instead of the original 100%. Now save this file as e.g. custom.css and pass it in the YAML header:
---
output:
html_document:
theme: cosmo
css: custom.css
---
And BTW you do not need to cat the results of pander :)

Related

Kable, Flextable, Huxtable to HTML: force the display of cell contents on a single line

I want the contents of my cells to be displayed in a single line. I'm using Rmarkdown to HTML.
But no matter which package I use (Kable, Flextable, Huxtable), the column width specification is ignored and a line break is introduced, which makes the very ugly and unreadable results.
In HTML, with a drop-down box, the total width shouldn't be a problem. I just want the results to be readable.
library(kableExtra)
library(flextable)
table = as.data.frame(matrix(rep("value [value1 - value2]",20), ncol = 10))
kbl(table) %>%
kable_paper() %>%column_spec(1:ncol(table), width = "3.5cm", bold = TRUE, italic = TRUE)%>%
scroll_box(width = "1000px", height = "500px")
tb = flextable(table)%>% flextable::width(width = 10)
knit_print(tb)
With flextable, this code forces (note the usage of autofit()) the display on one single line:
library(flextable)
as.data.frame(matrix(rep("value [value1 - value2]", 20), ncol = 10)) %>%
flextable()%>% theme_box() %>% autofit()
This will produce a table display in an HTML window, this window has a width that is limited (the size of your window or the max-width of your HTML page). If the width of the browser window is less than the width of the table, it will be compressed to fit the window or the available space.
If you need to make this flextable horizontally scrollable (it is already implemented for bookdown but not yet for all HTML format), you can add this CSS code to your r markdown so that flextables can be scrollable (soon integrated into flextable then soon not necessary):
```{css echo=FALSE}
.flextable-shadow-host{
overflow: scroll;
white-space: nowrap;
}
```
An HTML 'R Markdown' document with it:
---
output: html_document
---
```{css echo=FALSE}
.flextable-shadow-host{
overflow: scroll;
white-space: nowrap;
}
```
```{r}
library(flextable)
as.data.frame(matrix(rep("value [value1 - value2]", 20), ncol = 10)) |>
flextable()|> theme_box() |> autofit()
```
Here is the huxtable equivalent:
as_hux(table) |>
set_width(1) |>
set_wrap(FALSE) |>
set_col_width("3.5cm") |>
quick_html()
which makes the table as wide as you want:

bookdown html formatting issue with gitbook and split_by

I am generating a gitbook report with Rstudio the bookdown package.
It is fairly simple in terms of underlying R code, just a few recent tweaks for:
reducing text to 80% of page width
using double columns and
adding line number in the R code displayed.
Everything works well, except when I added "split_by: rmd" in the _output.yml. When doing so the resulting output doesn't respect the margin around the text anymore.
I don't know much about html yet, but looking at the html inspector revealed that the sections are located outside the inner-page formatting when using "split_by: rmd"
Default (no split_by argument):
With split_by: rmd
This is a shot in the dark as I cannot share the code and I am not able to reproduce the error with the minimal bookdown example from Yihui: https://github.com/rstudio/bookdown-demo.
Any leads to identify the origin of the error or even better propose a solution would be very welcomed!
Building the book from a R script:
bookdown::render_book(
input = "index.Rmd",
output_format = "bookdown::gitbook",
output_dir = paste0("gitbook-", format(Sys.time(), format = "%Y-%m-%d-%H%M%S"))
)
index.rmd YAML header:
---
title: "blahblah"
subtitle: "blahblahblah"
author: "DRAFT"
date: "August 2020"
documentclass: article
fontsize: 12pt
geometry: margin=2cm
link-citations: yes
#mainfont: Arial
bibliography: packages.bib
site: bookdown::bookdown_site
biblio-style: apalike
urlcolor: blue
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, eval = FALSE, attr.source='.numberLines')
table_format <- knitr::opts_knit$get('rmarkdown.pandoc.to')
if (table_format %in% c("html", "latex")) {
library(kableExtra)
knitr::opts_chunk$set(fig.pos='H', fig.align='center', out.width='80%')
}
## Automatically create a bib database for R packages
knitr::write_bib(c(.packages(), 'bookdown', 'knitr', 'rmarkdown', 'Hmisc'), 'packages.bib')
```
_output.yml:
bookdown::gitbook:
css: style.css
config:
toc:
before: |
<li>My book title</li>
#after: |
# <li>Published with bookdown</li>
edit: null
download: null
sharing: null
info: null
split_bib: FALSE
split_by: rmd
style.css:
p.caption {
color: #777;
margin-top: 10px;
}
p code {
white-space: inherit;
}
pre {
word-break: normal;
word-wrap: normal;
}
pre code {
white-space: inherit;
}
/* watermark for draft report
.watermark {
opacity: 0.2;
position: fixed;
top: 45%;
left: 45%;
font-size: 500%;
color: #606099;
z-index: 1000000;
}
*/
.book .book-body .page-wrapper .page-inner {
max-width: 80% !important;
}
/* Increase space to display line number in R chunks correctly */
pre.numberSource code > span > a:first-child::before {
left: -0.3em;
}
/* for multi cols */
/*.cols {display: flex; } /* uncomment for flex column size */
.cols {display: grid; grid-template-columns: 30% 50% 20%;} /* for fixed column size */
I found that the origin of the problem was the \newpage I added at the beginning of each rmd file for building the report in pdf format.
Solution 1: was to change split_by: rmd to split_by: section as my rmd files correspond mostly to level 2 sections.
Solution 2: was to put a wrapper around \newpage so that they are not evaluated when the output is html:
`r if (knitr::opts_knit$get('rmarkdown.pandoc.to') != "html") '
\\newpage
'`
Other approaches to solution 2 have been described here:
How to add \newpage in Rmarkdown in a smart way?

r knitr kable padding not working with format = "html"

I am trying to add padding to a table I am creating in an RMarkdown file that will generate both a pdf and an html flexdashboard. I know that there are a number of functions/packages I could use (pander, xtable, DT, etc.), but I would prefer to use the kable function from the knitr package.
The trouble I am having is that the padding argument does not seem to work. I would appreciate any help in solving this without having to add custom CSS to my document.
As a example, I have tried to run the code with padding set to 0, 10, 20 but the tables all look identical in the html file.
knitr::kable(head(cars), format = "html", padding = 0)
knitr::kable(head(cars), format = "html", padding = 10)
knitr::kable(head(cars), format = "html", padding = 20)
I am using knitr_1.14 and rmarkdown_1.0, and my session information is as follows.
R version 3.3.0 (2016-05-03)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
The option table.attr='cellpadding="20px"' does not work for me. Using CSS styles and adding a class to the table with table.attr='class="myTable"' leads to all tables having the desired padding property (even if only one table carries the new class).
If I only want to modify one single table I usually go with jQuery:
---
title: "Table Cell Padding"
output: html_document
---
```{r}
knitr::kable(head(cars), format = "html")
```
```{r}
knitr::kable(head(cars), format = "html", table.attr='class="myTable"')
```
<style>
.myTable td {
padding: 40px;
}
</style>
Another option is to use jQuery to edit individual elements. The following example modifies the table in the same way as the CSS styles above.
<script type="text/javascript">
// When the document is fully loaded...
$(document).ready(function() {
// ... select the cells of the table that has the class 'myTable'
// and add the attribute 'padding' with value '20px' to each cell
$('table.myTable td').css('padding','20px');
});
</script>
Here I add the class myTable to the table I want to modify. Afterwards I execute some JavaScript (see comments).
You could add any other CSS property to the table elements (or the table itself $('table.myTable').css(...)) in the same way (e.g. $('table.myTable td').css('background-color','red');)

Removing border from images using slidify reveal.js

here is the code of a slide with an r chunk and a graph:
---
```{r, echo=FALSE, warning=FALSE}
dd<-data.frame(x=1:10, y=21:30)
library(ggplot2)
ggplot(dd, aes(x,y)) + geom_point(color="red", size=6) +
theme(plot.background=element_rect(fill="gray7", color="gray7"),
panel.background=element_rect(fill="gray7"),
axis.line=element_line(color="white"),
panel.grid=element_blank(),
axis.text=element_text(color="white", size=rel(1.3)),
axis.title=element_text(color="white", size=rel(1.3))
)
```
---
this is my YAML:
---
framework : revealjs
revealjs : {theme: night, transition: none, center: "false"}
highlighter : highlight.js
hitheme : github
widgets : [mathjax]
mode : selfcontained
url : {lib: ./libraries}
knit : slidify::knit2slides
assets:
js:
- "http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"
- "http://bartaz.github.io/sandbox.js/jquery.highlight.js"
---
This gives this plot on the slide:
Obviously the border is there because this is the default for the reveal.js theme. I'm ok with the border on most slides, however for graphs being produced by some R chunks, I don't want it. I'm finding it hard to remove this simply. I have a hacky work-around. I don't include the output of the chunk and then I use some html to refer to the image that's just been named and saved to my assets/fig folder:
```{r, echo=FALSE, warning=FALSE, chunk_name, include=FALSE}
dd<-data.frame(x=1:10, y=21:30)
library(ggplot2)
ggplot(dd, aes(x,y)) + geom_point(color="red", size=6) +
theme(plot.background=element_rect(fill="gray7", color="gray7"),
panel.background=element_rect(fill="gray7"),
axis.line=element_line(color="white"),
panel.grid=element_blank(),
axis.text=element_text(color="white", size=rel(1.3)),
axis.title=element_text(color="white", size=rel(1.3))
)
```
<img src="assets/fig/chunk_name-1.png" style="background:none; border:none; box-shadow:none;">
---
This gives this output:
This is ok, but it doesn't seem the right way to do this and I can see how this might not work in all situations. Is there a better way to get rid of borders for the graphical output of r-chunks ?
edit: For the color aficionados, #111111 is the reveal.js background color, so would have been better to use that.
Ramnath actually gave me some advice as to the answer to this question:
into assets/css put this...
.noborder .reveal section img {
background:none;
border:none;
box-shadow:none;
}
Then refer to this css using the following at the beginning of your slide header:
--- ds:noborder
and obviously, include=T in the R chunk.

Very wide graphics in knitr HTML

I am using r markdown and Rstudio to create an html report. I have some graphics that I would like to be extremely wide, however, there seems to be a limit to the width in the output even when using fig.width and out.width in the chunk options. For instance the following three code chunks produce figures which are the same width in the final output:
```{r,fig.height=7,fig.width=12,echo=FALSE}
plot(rnorm(1000),type="l")
```
```{r,fig.height=7,fig.width=40,echo=FALSE}
plot(rnorm(1000),type="l")
```
```{r,fig.height=7,fig.width=40,echo=FALSE,out.width=20000}
plot(rnorm(1000),type="l")
```
I have used options(width=LARGENUMBER) for output (e.g. such as print, etc.) which seems to work well for printing tables, but I have yet to find a a way to make these graphs any wider.
Any suggestions?
You could add something like this
---
output: html_document
---
<style>
img {
max-width: none;
/* other options:
max-width: 200%;
max-width: 700px;
max-width: 9in;
max-width: 25cm;
etc
*/
}
</style>
```{r,fig.height=7,fig.width=12,echo=FALSE}
plot(rnorm(1000),type="l")
```
```{r,fig.height=7,fig.width=40,echo=FALSE}
plot(rnorm(1000),type="l")
```
```{r,fig.height=7,fig.width=40,echo=FALSE}
plot(rnorm(1000),type="l")
```
or better yet set up your knitr.css file with
img {
max-width: 200%;
}
or whatever you like, and use
---
output:
html_document:
css: ~/knitr.css
---