Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knitr::kable is there a way to reduce the font size?

I am using this code chunk

```{r, echo = FALSE}
  knitr::kable(df)
```

However I would like to reduce the size of all font inside this table so that the output looks nicer. Is there a way to do that with kable or is there another package which supports it?

like image 391
RockScience Avatar asked Nov 28 '16 09:11

RockScience


People also ask

What does Kable function do in R?

The kable() function in knitr is a very simple table generator, and is simple by design. It only generates tables for strictly rectangular data such as matrices and data frames. You cannot heavily format the table cells or merge cells.

How do I change font size in Rmarkdown HTML?

To change the font size, you don't need to know a lot of html for this. Open the html output with notepad ++. Control F search for "font-size". You should see a section with font sizes for the headers (h1, h2, h3,...).

What package is Kable in R?

The kableExtra package (Zhu 2021) is designed to extend the basic functionality of tables produced using knitr::kable() (see Section 10.1).


4 Answers

You can also try library(kableExtra). It has a lot of options to customise the table.

Specifically, for font size: https://haozhu233.github.io/kableExtra/awesome_table_in_html.html#font_size

df %>%
  kable("html") %>%
  kable_styling(font_size = 7)
like image 77
Christoph Safferling Avatar answered Oct 11 '22 02:10

Christoph Safferling


I use \tiny before the function and \normalsize after it, which works for .pdf using the formats latex and markdown.

like image 39
JAQuent Avatar answered Oct 11 '22 01:10

JAQuent


When you are happy with a global setting, use css on .table. To set it for one table, the only method I am aware of uses a div. Both methods cannot be used for latex etc, but the global method looks cleaner to me, because formating is delegated to a separate css.

---
title: "Small kable"
output: 
  html_document:
    css: kable.css

---

# Global setting

```{r}
library(knitr)
kable(iris[1:5,])
```


# Local setting, not portable
<div class="verysmall">

```{r}
kable(iris[1:5,])
```

</div>

CSS File

.table{
  width:auto;
  font-size: 12px;
}

.verysmall .table{
  font-size: 8px;
}

I also use auto-formatting for kable-tables in most cases.

like image 6
Dieter Menne Avatar answered Oct 11 '22 00:10

Dieter Menne


Dieter's answer worked for me. My first time using CSS in rmarkdown. Instead of using a separate CSS file, I embedded the following code towards the top of my rmarkdown doc, as referenced here: https://bookdown.org/yihui/rmarkdown-cookbook/html-css.html.

    ```{css, echo = FALSE}
    .verysmall .table{
      font-size: 8px;
    }
    ```
like image 1
Haariss Avatar answered Oct 11 '22 00:10

Haariss