xtable + knitr set column width html - html

How can I set the column widths of individual columns in the knitr (Rmd) output of a code chunk using the xtable package?
MWE
```{r setup, include=FALSE}
library(xtable)
```
```{r, results="asis", echo=FALSE}
print(xtable(mtcars[1:2, 1:2]), type="html", include.rownames=FALSE)
```
Lets say I want to make column_#1 - 2 inches wide and column_#2 - 3 inches wide.
I'm not married to xtable here but don't know of any other html table out packages that could do this.

You can change the css used by xtable to format the table and change columns width. It does not allow changing individual columns though.
See http://nsaunders.wordpress.com/2012/08/27/custom-css-for-html-generated-using-rstudio/
An example below:
Add a stylesheet (here named custom.css) to the same folder as your markdown file.
table {
max-width: 95%;
border: 1px solid #ccc;
}
th {
background-color: #000000;
color: #ffffff;
width: 100px;
}
td {
background-color: #dcdcdc;
width: 100px;
}
and set the options to use this stylesheet
```{r setup, include=FALSE}
library(xtable)
options(rstudio.markdownToHTML =
function(inputFile, outputFile) {
require(markdown)
markdownToHTML(inputFile, outputFile, stylesheet='custom.css')
}
)
```
```{r, results="asis", echo=FALSE}
print(xtable(mtcars[1:2, 1:2]), type="html", include.rownames=FALSE)
```
It might be possible to hack the print.xtable function to get more flexibility.

Related

Centering Rmarkdown knitrbootstrap Report

Found this package called knitrBootstrap Which is to allow for Bootstrap style web pages when reporting in Rmarkdown.
Note: I am using the klippy, kableExtra, and knitrBootstrap
My issue is that when rendered is does not center the whole report, it is stuck to one side. And also the Title of the Document doesn't get displayed? Any suggestions to give this HTML page a more "fuller" feel? Because I can insert straight HTML code in Rmarkdown I added the HTML tag
---
output:
knitrBootstrap::bootstrap_document:
title: "Test file"
theme: united
highlight: sunburst
---
```{r}
library(kableExtra)
library(klippy)
library(knitrBootstrap)
```
```{r echo=FALSE, include=TRUE, out.width="100%"}
mpg_list <- split(mtcars$mpg, mtcars$cyl)
disp_list <- split(mtcars$disp, mtcars$cyl)
inline_plot <- data.frame(cyl = c(4, 6, 8), mpg_box = "", mpg_hist = "",
mpg_line1 = "", mpg_line2 = "",
mpg_points1 = "", mpg_points2 = "", mpg_poly = "")
inline_plot %>%
kbl(booktabs = TRUE) %>%
kable_paper(full_width = FALSE) %>%
column_spec(2, image = spec_boxplot(mpg_list)) %>%
column_spec(3, image = spec_hist(mpg_list)) %>%
column_spec(4, image = spec_plot(mpg_list, same_lim = TRUE)) %>%
column_spec(5, image = spec_plot(mpg_list, same_lim = FALSE)) %>%
column_spec(6, image = spec_plot(mpg_list, type = "p")) %>%
column_spec(7, image = spec_plot(mpg_list, disp_list, type = "p")) %>%
column_spec(8, image = spec_plot(mpg_list, polymin = 5))
```
I can't seem to find a ton of literature on the format you're using. However, I did notice that it doesn't change size when the screen size changes. It is all just set to one final size. That being said, the table thinks it is centered. In reality, it is formatted to 'fit' the contents, but the table is set to fill a space so that that outer space is centered in the body, but the table is left-aligned in that available space. On top of all that, the body is set to a max-width of 36em. That's why it looks left-aligned.
Clear as mud, I know. Sigh.
I can help make it better, but a different output format may be a better option. Almost any method I tried to make the table bigger destroyed the plots' SVG (distorted them).
This worked, but I don't know if the juice is worth the squeeze.
Add these styles between chunks and keep your code the same.
<style>
body {
max-width: 100%; // 36 em isn't working for me
}
table{
width: 924px !important;
height: auto;
}
tr {
height: 4em;
width: 924px !important; // 28 + (7*128) (for the 8 columns)
}
td {
vertical-align: middle !important;
padding-bottom: 0px !important;
}
svg {
width: 110%;
height: auto; // keep the aspect ratio
}
thead > tr *:not(:first-child) {
width: 128px; // only set here, if set to all td, it blows the svg
}
</style>
If you have any questions, let me know.
This centers, without centering, by filling the available space.

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?

Set cell width in knitr/pandoc?

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

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