Is it possible to format captions in kableExtra? I would like to center and bold a caption for a table when knitting to HTML in RMarkdown. I have tried to wrap the table in a CSS div where the text was centered, but this did not produce the intended result.
Sample table:
library(kableExtra)
kable(data.frame(a = 1:3, b = 4:6), caption = "CENTER") %>%
kable_styling(bootstrap_options = "striped")
Yields:
I would like:
If the final format is HTML:
write caption within HTML center and strong tag and set escape to FALSE.
kable(
data.frame(a = 1:3, b = 4:6),
caption = "<center><strong>CENTER</strong></center>",
escape = FALSE,
format = "html"
) %>%
kable_styling(bootstrap_options = "striped")
There is a solution through css stylesheets. The trick is to identify the correct element. Let's assume a default html document.
---
title: "test"
css: template.css
output: html_document
---
The following css script will work.
.table-wrapper caption {
color: black;
text-align: center;
font-family: Arial;
font-weight: bold;
font-size: xx-large;
}
When in doubt, you can always identify the appropriate element by opening the html document in your browser and inspecting it via ctrl+shift+c.
Related
I am including gt tables in a Rmarkdown Tufte-style HTML. I want to align the gt tables in the center of the main column, rather than in the center of the HTML spanning both the main column and margin. I have tried using the fig.align knitr option as well as tab.align command. Here is a repo with an rmd that shows the problem: https://github.com/cassidybargell/gt-tufte. The gt table spans the main column as well as the margin.
Example code of a gt table being used in the Tufte-HTML:
tibble(subject = "Joe",
ytreat = "13",
ycontrol = "9",
ydiff = "+4") %>%
gt()
Make your own css file is one way to fix it. Here are the lines of code:
.gt_table {
margin-left: 0 !important;
margin-right: 0 !important;
width: 55% !important;
}
Thank you to Yaodong Yu for the help!!
An alternative is to define a hook function:
knitr::knit_hooks$set(gtbl = function(before, options){
if (before) {
paste( '<style> .gt_table {width: 100% !important;} </style>',
'<div class="figure"><p class="caption marginnote shownote">',
options$fig.cap,
'</p>',
sep="")
} else { "</div>" }
})
inside a chunk. Then the chunk option gtbl can be used when a gt table is required as for example:
```{r gtbl=TRUE, fig.cap="*Table 1* Energy Trends"}
tblTrends()
```
where fig.cap supplies the caption right-aligned.
Hook functions are documented in the rmarkdown cookbook
I am using pagedown::chrome_print() to convert slidy presentations created with Rmarkdown to pdf -- it does a better job than saving as PDF from Chrome. However, despite studying the help file, I cannot figure out how to add page numbers. Is there a way to do this?
(Note that pagedown here refers to the R package, not the JavaScript markdown previewer.)
Sorry if the help page is not clear on this point.
It is possible to pass header/footer options to Chrome using pagedown::chrome_print().
These options are the ones defined by the Chrome DevTools Protocol for the Page.printToPDF method.
You can customise the header and the footer with an HTML template. Chrome also offers the following values: date, title, url, pageNumber and totalPages.
Following the explanations on this help page, here is an example to print the page numbers:
library(htmltools)
footer <- div(
style = "font-size: 8pt; text-align: right; width: 100%; padding-right: 12pt;",
span(class = "pageNumber"), "/", span(class = "totalPages")
)
pagedown::chrome_print(
"slidy.Rmd",
options = list(
landscape = TRUE,
displayHeaderFooter = TRUE,
footerTemplate = format(footer, indent = FALSE),
marginTop = 0,
marginBottom = 0.4
)
)
I got it to work with a custom CSS file. I created a file called custom.css and included in that file was
#page {
#bottom-right {
content: counter(page);
}
}
Then I used that along with the other pagedown defaults with a header like this
title: "My Report"
output:
pagedown::html_paged:
css: ["custom.css", "default-fonts", "default"]
I am using rmarkdown to generate an HTML report. I am on a restricted machine, can't install tex. So, I was trying to generate an HTML document and then convert/print it to a pdf. The example markdown document is:
---
title: "trials"
author: "Foo Bar"
date: "15 December 2016"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r cars, echo=FALSE, cache=FALSE, message=FALSE}
library(dplyr, quietly = TRUE)
library(abind, quietly = TRUE)
virginica <- iris %>% filter(Species == "virginica") %>% head() %>% select(-Species)
setosa <- iris %>% filter(Species == "setosa") %>% head() %>% select(-Species)
diff_mat <- virginica - setosa
diff_mat[diff_mat<0] <- '<font color="green">⇓ </font>'
diff_mat[diff_mat>0] <- '<font color="red">⇑ </font>'
diff_mat[diff_mat == 0] <- '<font color="blue">⇔ </font>'
datArray <- abind::abind(virginica, diff_mat, along=3)
fin_dat <- apply(datArray,1:2, function(x)paste(x[1],x[2], sep = " "))
knitr::kable(fin_dat, format = "html",
escape = FALSE, table.attr = "border=1",
caption = "Changes across species")
```
I can't knit to word either as the formatting is lost as discussed in HTML formatted tables in rmarkdown word document. The HTML produced is exactly what I wanted. HTML to word using save as in word works mostly fine with some issues and I can print pdf but it is not as good as directly printed from pdf.
when I try to save it as pdf in chrome the colour is lost.
There is no issues in print options
Other pages such as this question in our beloved site Replace NA's using data from Multiple Columns prints fine
Do you have any pointers where I am missing a point or where the issue is.
Add this right after the YAML header:
<style>
#media print {
font[color="green"] {
color: #00ff00!important;
-webkit-print-color-adjust:exact;
}
font[color="red"] {
color: #ff0000!important;
-webkit-print-color-adjust:exact;
}
}
</style>
The problem is that RStudio's default R markdown templates use Bootstrap and their version of bootstrap.min.css has:
#media print {
*,
*:before,
*:after {
color: #000 !important;
text-shadow: none !important;
background: transparent !important;
-webkit-box-shadow: none !important;
box-shadow: none !important;
}
in it. That's a pretty "destructive" media query as the *'s cause those settings to be applied to all tags and color: #000 !important; means "no color for YOU!" when you print a document. I grok the sentiment behind that (saving the planet + toner/ink costs) but if you're printing to PDF it makes no sense whatsoever.
Unfortunately, there are no hyper-targeted media queries for printing to PDF, so the generic "print" ones get applied when you print web pages to PDFs and these mindless, catch-all media queries take over.
The problem for you is that you'll need to be very specific in targeting any other tags to override these settings. Which means adding your own CSS classes to anything you generate in Rmds or getting cozy with "Inspect Element" until you catch'em all.
However, if you're feeling adventurous you can modify the YAML header to be:
output:
html_document:
self_contained: false
When you render to HTML it'll create a directory with subdirectories for the various components vs base64-encode them into one big document.
I named my document forso.Rmd which means it made a directory called forso_files and put subdirs under it.
Open up the main HTML file and scroll down until you see something like:
<script src="forso_files/jquery-1.11.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="forso_files/bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="forso_files/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="forso_files/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="forso_files/bootstrap-3.3.5/shim/respond.min.js"></script>
<script src="forso_files/navigation-1.1/tabsets.js"></script>
Change this:
<link href="forso_files/bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" />
to:
<link href="forso_files/bootstrap-3.3.5/css/bootstrap.css" rel="stylesheet" />
Edit bootstrap.css, remove the color: #000 !important; line and add the -webkit-print-color-adjust:exact; line. SAVE A COPY OF bootstrap.css ELSEWHERE as it'll get squashed on future renders (i.e. you'll need to copy it back on every render).
You can't just link to a separate CSS file with a less brain dead print media query since the color: #000 !important; impacts all tags thanks to the * target and you can't just reset it to initial or inherit` because that will just turn them black as well.
Your final (and probably best) option is to make your own R Markdown template (see https://github.com/hrbrmstr/markdowntemplates for more info) and avoid placing over-arching print media queries in it.
I would like to add spacing or padding to a html table generated by xtable.
The print.xtable() parameter html.table.attributes doesn't work for me.
Here an example chunk that can be pasted in a Rmd document.
```{r results='asis'}
library(xtable)
print(xtable(cars), type='html',
html.table.attributes = 'cellspacing="5" cellpadding="5"',
include.rownames = FALSE, include.colnames=FALSE,
comment = FALSE)
```
It's a simple standalone example and I wouldn't like to create a css file for this: more details on the purpose.
You can add CSS rules to a style sheet in the R Markdown document with the style tags.
<style>
th,td{
padding:2px 5px 2px 5px;
}
</style>
I have an RMarkdown document outputting to HTML of the same form as the below example. What do I add where to apply unique CSS ids or classes to each plot output?
---
title: "RMarkdown"
author: "Me"
date: "Friday, March 27, 2015"
output:
html_document:
theme: null
css: style.css
---
```{r plot1, echo=FALSE, warning=FALSE, message=FALSE}
library(ggplot2)
x <- ggplot(some_r_code)
print(x)
```
```{r plot2, echo=FALSE, warning=FALSE, message=FALSE}
y <- ggplot(some_more_r_code)
print(y)
```
I've read the info page at http://rmarkdown.rstudio.com/html_document_format.html that went a ways to answering this question but didn't get me there. I have a similar question referencing the material in that page in it's comment section, and would appreciate an answer on either.
Thanks!
You can tell knitr (which is used under the hood) with results="asis" to embed a chunk's output directly into the html. Within the chunk you can use cat to simply write a style tag including your css definitions:
```{r results="asis"}
cat("
<style>
h1 {
color: red;
}
</style>
")
```
See http://yihui.name/knitr/options/#chunk_options for details.
Declaring custom css in RMarkdown
Add css between <style> and </style> tags in the regular body of the RMarkdown (i.e. not in R code area), like so:
<style>
.pad {
padding-top: 200px;
}
</style>
# This heading will be padded {.pad}
Another option is to declare css: "style.css" in yaml and store styles in a separate file (style sheet) in the same directory
Or css can be generated and applied via R code (excellent example here)
Open the resultant HTML in a browser with a Developer Tools option and look at the generated HTML. Then apply you styling to the appropriate tags/classes. For example, put the following into style.css, knit the file and you should see a red border on the plots:
img {
background-color: red;
padding: 2px;
border: 1px solid red;
border-radius: 3px;
margin: 0 5px;
max-width: 100%;
}