4 Styling
In this chapter, we’re styling our tables. This means we’re going to customize their theme. To do so, let us bring back our last table from Chapter 1. This is the table we’ll customize.
In this chapter, we don’t really need the code of that table. So, I will only reprint the code in a folded section. Just know that the table is saved in a variable penguins_table
.
Code
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.4.0 ✔ purrr 0.3.5
## ✔ tibble 3.1.8 ✔ dplyr 1.0.10
## ✔ tidyr 1.2.1 ✔ stringr 1.4.1.9000
## ✔ readr 2.1.3 ✔ forcats 0.5.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
library(gt)
<- palmerpenguins::penguins |> filter(!is.na(sex))
penguins <- penguins |>
penguin_counts mutate(year = as.character(year)) |>
group_by(species, island, sex, year) |>
summarise(n = n(), .groups = 'drop')
<- penguin_counts |>
penguin_counts_wider pivot_wider(
names_from = c(species, sex),
values_from = n
|>
) # Make missing numbers (NAs) into zero
mutate(across(.cols = -(1:2), .fns = ~replace_na(., replace = 0))) |>
arrange(island, year)
<- colnames(penguin_counts_wider)
actual_colnames <- actual_colnames |>
desired_colnames str_remove('(Adelie|Gentoo|Chinstrap)_') |>
str_to_title()
names(desired_colnames) <- actual_colnames
<- penguin_counts_wider |>
penguins_table mutate(across(.cols = -(1:2), ~if_else(. == 0, NA_integer_, .))) |>
mutate(
island = as.character(island),
year = as.numeric(year),
island = paste0('Island: ', island)
|>
) gt(groupname_col = 'island', rowname_col = 'year') |>
cols_label(.list = desired_colnames) |>
tab_spanner(
label = md('**Adelie**'),
columns = 3:4
|>
) tab_spanner(
label = md('**Chinstrap**'),
columns = c('Chinstrap_female', 'Chinstrap_male')
|>
) tab_spanner(
label = md('**Gentoo**'),
columns = contains('Gentoo')
|>
) tab_header(
title = 'Penguins in the Palmer Archipelago',
subtitle = 'Data is courtesy of the {palmerpenguins} R package'
|>
) sub_missing(missing_text = '-') |>
summary_rows(
groups = TRUE,
fns = list(
'Maximum' = ~max(.),
'Total' = ~sum(.)
),formatter = fmt_number,
decimals = 0,
missing_text = '-'
|>
) tab_options(
data_row.padding = px(2),
summary_row.padding = px(3), # A bit more padding for summaries
row_group.padding = px(4) # And even more for our groups
|>
) opt_stylize(style = 6, color = 'gray')
penguins_table
Penguins in the Palmer Archipelago | ||||||
Data is courtesy of the {palmerpenguins} R package | ||||||
Female | Male | Female | Male | Female | Male | |
---|---|---|---|---|---|---|
Island: Biscoe | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total | ||||||
Island: Dream | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total | ||||||
Island: Torgersen | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total |
4.1 Theming
The easiest way to style a table is to apply a pre-installed theme via opt_stylize()
. We’ve already done that in the first chapter because it’s really easy to do. But there’s nothing stopping us from overwritting the theme. Just apply another opt_stylize()
layer to the table.
|>
penguins_table opt_stylize(style = 6, color = 'pink')
Penguins in the Palmer Archipelago | ||||||
Data is courtesy of the {palmerpenguins} R package | ||||||
Female | Male | Female | Male | Female | Male | |
---|---|---|---|---|---|---|
Island: Biscoe | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total | ||||||
Island: Dream | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total | ||||||
Island: Torgersen | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total |
4.1.1 Tab options
Next, we can tweak our table’s appearance with tab_options()
. It’s basically the analogue of theme()
in {ggplot2}
. In Chapter 1, we’ve already used tab_options()
to apply three small changes. Once again, there’s no harm in applying another layer of the same stuff.
|>
penguins_table tab_options(
# These were the ones we applied in the first chapter
data_row.padding = px(2),
summary_row.padding = px(3), # A bit more padding for summaries
row_group.padding = px(4) # And even more for our groups
)
Penguins in the Palmer Archipelago | ||||||
Data is courtesy of the {palmerpenguins} R package | ||||||
Female | Male | Female | Male | Female | Male | |
---|---|---|---|---|---|---|
Island: Biscoe | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total | ||||||
Island: Dream | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total | ||||||
Island: Torgersen | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total |
But let’s change a couple of things. Warning: These changes may or may not “improve” the table. We’ll just apply stuff to learn what’s going on. We can worry about aesthetics later.
We’ll start by styling the heading a little bit. All of the arguments in tab_options()
that target the header start with heading.
|>
penguins_table tab_options(
# These were the ones we applied in the first chapter
data_row.padding = px(2),
summary_row.padding = px(3), # A bit more padding for summaries
row_group.padding = px(4) # And even more for our groups
|>
) # Change header theme
tab_options(
heading.align = 'left',
heading.background.color = 'darkgreen',
heading.title.font.size = px(20)
)
Penguins in the Palmer Archipelago | ||||||
Data is courtesy of the {palmerpenguins} R package | ||||||
Female | Male | Female | Male | Female | Male | |
---|---|---|---|---|---|---|
Island: Biscoe | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total | ||||||
Island: Dream | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total | ||||||
Island: Torgersen | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total |
Next, let us attack our column labels. We’ll do two things:
- Change the background color (simple)
- Remove the bottom border line (A bit tricky. You’ll see why in a sec.)
To achieve the latter thing, you need to change border-style
. The most common are solid
, dashed
, dotted
and none
. Guess which one we’re choosing.
|>
penguins_table tab_options(
# These were the ones we applied in the first chapter
data_row.padding = px(2),
summary_row.padding = px(3), # A bit more padding for summaries
row_group.padding = px(4) # And even more for our groups
|>
) # Change header theme
tab_options(
heading.align = 'left',
heading.background.color = 'darkgreen',
heading.title.font.size = px(20)
|>
) tab_options(
column_labels.background.color = 'yellow',
column_labels.border.bottom.style = 'none'
)
Penguins in the Palmer Archipelago | ||||||
Data is courtesy of the {palmerpenguins} R package | ||||||
Female | Male | Female | Male | Female | Male | |
---|---|---|---|---|---|---|
Island: Biscoe | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total | ||||||
Island: Dream | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total | ||||||
Island: Torgersen | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total |
The effect of the color change is clearly visible. But what’s that? There is still a line below the column labels. The reason for this is simple: There is no border below the column_labels
area anymore. But there is still a border above the table_body
and the row_group
. Yes, that’s right. You can only remove one line at the cost of three1.
|>
penguins_table tab_options(
# These were the ones we applied in the first chapter
data_row.padding = px(2),
summary_row.padding = px(3), # A bit more padding for summaries
row_group.padding = px(4) # And even more for our groups
|>
) # Change header theme
tab_options(
heading.align = 'left',
heading.background.color = 'darkgreen',
heading.title.font.size = px(20)
|>
) tab_options(
column_labels.background.color = 'yellow',
column_labels.border.bottom.style = 'none',
row_group.border.top.style = 'none',
table_body.border.top.style = 'none'
)
Penguins in the Palmer Archipelago | ||||||
Data is courtesy of the {palmerpenguins} R package | ||||||
Female | Male | Female | Male | Female | Male | |
---|---|---|---|---|---|---|
Island: Biscoe | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total | ||||||
Island: Dream | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total | ||||||
Island: Torgersen | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total |
So how do you find out which areas might affect whatever it is that you want to style? Lucky for us, the gt docs have a neat image that shows you the areas of a {gt}
table.
There’s one more way to find out what border you need to overwrite and we’ll talk about it in Section 4.2. For now, let me show you how you can target even more specific parts of your table.
4.1.2 Cell styling
Imagine that you want to turn the Chinstrap column spanner blue (for whatever reason). You have seen that you can target only all column labels and all column spanners with tab_options()
. For very specific wishes (like this one), there’s tab_style()
.
This function has two arguments: locations
and style
. Does this remind you of something? That’s right, it’s very similar to text_transform()
which you learned in Chapter 2. But instead of applying a text transformation function to a cell, we apply a style.
Now, to specify locations
and style
we have two sets of helper functions. The location helpers translate more or less to the areas that you see in Figure 4.1.
Location helpers
cells_body()
cells_column_labels()
cells_column_spanners()
cells_footnotes()
cells_grand_summary()
cells_row_groups()
cells_stub()
cells_stub_grand_summary()
cells_stub_summary()
cells_stubhead()
cells_summary()
cells_title()
Style helpers
cell_borders()
cell_fill()
cell_text()
Applying these helpers is pretty straightforward. Just use them for either locations
or style
in tab_style()
. For example, we can use cells_column_spanners()
to target all column spanners. And with cell_fill()
we can turn them blue.
|>
penguins_table tab_options(
# These were the ones we applied in the first chapter
data_row.padding = px(2),
summary_row.padding = px(3), # A bit more padding for summaries
row_group.padding = px(4) # And even more for our groups
|>
) # Change header theme
tab_options(
heading.align = 'left',
heading.background.color = 'darkgreen',
heading.title.font.size = px(20)
|>
) tab_options(
column_labels.background.color = 'yellow',
column_labels.border.bottom.style = 'none',
row_group.border.top.style = 'none',
table_body.border.top.style = 'none'
|>
) tab_style(
locations = cells_column_spanners(),
style = cell_fill(color = 'dodgerblue')
)
Penguins in the Palmer Archipelago | ||||||
Data is courtesy of the {palmerpenguins} R package | ||||||
Female | Male | Female | Male | Female | Male | |
---|---|---|---|---|---|---|
Island: Biscoe | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total | ||||||
Island: Dream | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total | ||||||
Island: Torgersen | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total |
Another cool way to target cells is tab_style_body()
. Basically, it is a combination of fmt()
from Chapter 3 and tab_style()
. So, you can apply a style to table cells that either match a regex, correspond to a specific value or fulfill criteria according to your own custom function. Here’s one example of that.
|>
penguins_table tab_options(
# These were the ones we applied in the first chapter
data_row.padding = px(2),
summary_row.padding = px(3), # A bit more padding for summaries
row_group.padding = px(4) # And even more for our groups
|>
) # Change header theme
tab_options(
heading.align = 'left',
heading.background.color = 'darkgreen',
heading.title.font.size = px(20)
|>
) tab_options(
column_labels.background.color = 'yellow',
column_labels.border.bottom.style = 'none',
row_group.border.top.style = 'none',
table_body.border.top.style = 'none'
|>
) tab_style(
locations = cells_column_spanners(),
style = cell_fill(color = 'dodgerblue')
|>
) tab_style_body(
fn = function(x) between(x, 5, 10),
style = cell_text(color = 'red', weight = 'bold')
)
Penguins in the Palmer Archipelago | ||||||
Data is courtesy of the {palmerpenguins} R package | ||||||
Female | Male | Female | Male | Female | Male | |
---|---|---|---|---|---|---|
Island: Biscoe | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total | ||||||
Island: Dream | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total | ||||||
Island: Torgersen | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total |
Unfortunately, this function works only on cells in the body. Thus we have to find some other way to target the Chinstrap column spanner. To make this work, we have to assign an ID to the column spanner. Then, we can target that ID within cells_column_spanners()
. Here’s a minimal example of how that works.
|>
exibble select(1:4) |>
gt() |>
opt_stylize(style = 3) |>
fmt_number(columns = 'num') |>
tab_spanner(
columns = 1:2,
label = 'A column spanner',
id = 'spannerA' ## That's the ID we can target
|>
) tab_spanner(
columns = 3:4,
label = 'Another column spanner',
id = 'spannerB' ## That's the ID we can target
|>
) tab_style(
locations = cells_column_spanners(spanners = 'spannerA'),
style = cell_fill(color = 'darkgreen')
|>
) tab_style(
locations = cells_column_spanners(spanners = 'spannerB'),
style = cell_fill(color = 'darkgreen', alpha = 0.5)
)
num | char | fctr | date |
---|---|---|---|
Applying this logic to our penguins table is straightforward. But you will have to copy the whole table code and insert an ID in the initial gt()
layer. I think you get the idea. So here’s only the result (unfold for full code).
Code
|>
penguin_counts_wider mutate(across(.cols = -(1:2), ~if_else(. == 0, NA_integer_, .))) |>
mutate(
island = as.character(island),
year = as.numeric(year),
island = paste0('Island: ', island)
|>
) gt(groupname_col = 'island', rowname_col = 'year') |>
cols_label(.list = desired_colnames) |>
tab_spanner(
label = md('**Adelie**'),
columns = 3:4
|>
) tab_spanner(
label = md('**Chinstrap**'),
columns = c('Chinstrap_female', 'Chinstrap_male'),
id = 'chinstrap'
|>
) tab_spanner(
label = md('**Gentoo**'),
columns = contains('Gentoo')
|>
) tab_header(
title = 'Penguins in the Palmer Archipelago',
subtitle = 'Data is courtesy of the {palmerpenguins} R package'
|>
) sub_missing(missing_text = '-') |>
summary_rows(
groups = TRUE,
fns = list(
'Maximum' = ~max(.),
'Total' = ~sum(.)
),formatter = fmt_number,
decimals = 0,
missing_text = '-'
|>
) tab_options(
data_row.padding = px(2),
summary_row.padding = px(3), # A bit more padding for summaries
row_group.padding = px(4) # And even more for our groups
|>
) opt_stylize(style = 6, color = 'gray') |>
tab_style(
locations = cells_column_spanners(spanners = 'chinstrap'),
style = cell_fill(color = 'dodgerblue')
)
Penguins in the Palmer Archipelago | ||||||
Data is courtesy of the {palmerpenguins} R package | ||||||
Female | Male | Female | Male | Female | Male | |
---|---|---|---|---|---|---|
Island: Biscoe | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total | ||||||
Island: Dream | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total | ||||||
Island: Torgersen | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total |
Notice that the grey border at the bottom of the Chinstrap column spanner looks kind of ugly. So, why not remove it? This is a great exercise of applying multiple styles. This is done by using multiple style helpers and collecting them in a list. The same works with location helpers. Here’s a small example again.
|>
exibble select(1:4) |>
gt() |>
opt_stylize(style = 3) |>
fmt_number(columns = 'num') |>
tab_spanner(
columns = 1:2,
label = 'A column spanner',
id = 'spannerA'
|>
) tab_spanner(
columns = 3:4,
label = 'Another column spanner',
id = 'spannerB'
|>
) tab_style(
locations = cells_column_spanners(spanners = 'spannerA'),
style = cell_fill(color = 'darkgreen')
|>
) tab_style(
locations = cells_column_spanners(spanners = 'spannerB'),
style = cell_fill(color = 'darkgreen', alpha = 0.5)
|>
) tab_style(
locations = list(
cells_column_labels(),
cells_body(
columns = c('char', 'date'), rows = c(3, 5, 8)
)
),style = list(
cell_fill(color = 'firebrick4'),
cell_text(color = 'white', size = 14, weight = 'bold'),
cell_borders(
sides = c('left', 'right'),
color = 'green',
weight = px(3)
)
) )
Now, applying the same logic to our Chinstrap column spanner should be easy, right? It is. But unfortunately, it didn’t help. Have a look for yourself. The border is still there.
Code
|>
penguin_counts_wider mutate(across(.cols = -(1:2), ~if_else(. == 0, NA_integer_, .))) |>
mutate(
island = as.character(island),
year = as.numeric(year),
island = paste0('Island: ', island)
|>
) gt(groupname_col = 'island', rowname_col = 'year') |>
cols_label(.list = desired_colnames) |>
tab_spanner(
label = md('**Adelie**'),
columns = 3:4
|>
) tab_spanner(
label = md('**Chinstrap**'),
columns = c('Chinstrap_female', 'Chinstrap_male'),
id = 'chinstrap'
|>
) tab_spanner(
label = md('**Gentoo**'),
columns = contains('Gentoo')
|>
) tab_header(
title = 'Penguins in the Palmer Archipelago',
subtitle = 'Data is courtesy of the {palmerpenguins} R package'
|>
) sub_missing(missing_text = '-') |>
summary_rows(
groups = TRUE,
fns = list(
'Maximum' = ~max(.),
'Total' = ~sum(.)
),formatter = fmt_number,
decimals = 0,
missing_text = '-'
|>
) tab_options(
data_row.padding = px(2),
summary_row.padding = px(3), # A bit more padding for summaries
row_group.padding = px(4) # And even more for our groups
|>
) opt_stylize(style = 6, color = 'gray') |>
tab_style(
locations = cells_column_spanners(spanners = 'chinstrap'),
style = list(
cell_fill(color = 'dodgerblue'),
cell_borders(style = 'hidden')
) )
Penguins in the Palmer Archipelago | ||||||
Data is courtesy of the {palmerpenguins} R package | ||||||
Female | Male | Female | Male | Female | Male | |
---|---|---|---|---|---|---|
Island: Biscoe | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total | ||||||
Island: Dream | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total | ||||||
Island: Torgersen | ||||||
2007 | ||||||
2008 | ||||||
2009 | ||||||
Maximum | ||||||
Total |
The reason why this is happening is simple. It’s a known bug. But that’s not a problem. Actually, that’s a great motivation for our next part.
Whenever styling does not work as expected, {gt}
allows you to sneak behind the HTML/CSS curtain. Then, you can manually apply whatever it is you want to apply.
I know that this may sound daunting but it’s actually quite manageable. I’ve learned most of what I know about HTML/CSS from styling my Quarto blog. And most of that happened via copy-and-paste. With a little bit of effort, you can do the same.
4.2 Custom CSS
Let’s do a HTML/CSS quick tour. First, let us start with something you’re already familiar with. You probably know that Markdown converts **blabla**
to blabla, i.e. bold text. This means that with the right decoration, you can turn blabla
into bold non-sense.
4.2.2 Classes and IDs
Just like your Markdown documents, websites are really just decorated texts. Every little tweak on a website can be accomplished by adding the right instruction into style=
.
Now, comes the good part. You don’t have to repeat your style instructions all the time. You can recycle your styles. That’s what CSS classes do.
Let’s imagine that we want to recycle our previous style that used color:blue;
, font-family:Merriweather;
and font-weight:bold;
. We can define a CSS class my-style
that encodes that information as follows.
.my-style {
color:blue;
font-family:Merriweather;
font-weight:bold;
}
Notice the .
at the beginning. That’s the secret class symbol in CSS. And that’s also the only thing we need to know to overwrite the gt_table
class to style our table like we want. The opt_css()
layer will help us to get the CSS code into our website.
library(gt)
|>
exibble gt() |>
opt_css(
'
.gt_table {
color:blue;
font-family:Merriweather;
font-weight:bold;
}
'
)
num | char | fctr | date | time | datetime | currency | row | group |
---|---|---|---|---|---|---|---|---|
Unfortunately, this did not change anything. Why? Because {gt}
is clever enough to encode its styling not only with a global CSS class like .gt_table
but also with a unique ID for every table. This ensures that you cannot accidentally change the styling of a different {gt}
table.
That’s why you can assign a custom ID for your table in gt()
and target that ID in your CSS code. The secret symbol for IDs in CSS is #
. Armed with that knowledge, let us try again.
library(gt)
|>
exibble gt(id = 'table_id') |>
opt_css(
'
#table_id .gt_table {
color:blue;
font-family:Merriweather;
font-weight:bold;
}
'
)
num | char | fctr | date | time | datetime | currency | row | group |
---|---|---|---|---|---|---|---|---|
Awesome. This worked. At least a bit. But the column labels remained the same. Here’s why.
The things that we want to change (color
, font-family
and font-weight
of the column labels) are not styled in the .gt_table
class. These are styled in .gt_col_heading
.
Hence, you need to target that class as well. Maybe with different instructions.
|>
exibble gt(id = 'table_id') |>
opt_css(
'
#table_id .gt_table {
color:blue;
font-family:Merriweather;
font-weight:bold;
}
#table_id .gt_col_heading {
color:red;
font-family:"Source Sans Pro";
font-weight:bold;
}
'
)
num | char | fctr | date | time | datetime | currency | row | group |
---|---|---|---|---|---|---|---|---|