fmt_icon | R Documentation |
We can draw from a library of thousands of icons and selectively insert them
into a gt table. The fmt_icon()
function makes this possible and it
operates a lot like fmt_flag()
in that input cells need to contain some
reference to an icon name. We are exclusively using Font Awesome icons here
(and we do need to have the fontawesome package installed) so the
reference is the short icon name. Multiple icons can be included per cell by
separating icon names with commas (e.g., "hard-drive,clock"
). The sep
argument allows for a common separator to be applied between flag icons.
fmt_icon(
data,
columns = everything(),
rows = everything(),
height = "1em",
sep = " ",
stroke_color = NULL,
stroke_width = NULL,
stroke_alpha = NULL,
fill_color = NULL,
fill_alpha = NULL,
vertical_adj = NULL,
margin_left = NULL,
margin_right = NULL,
a11y = c("semantic", "decorative", "none")
)
data |
The gt table data object
This is the gt table object that is commonly created through use of the
|
columns |
Columns to target
Can either be a series of column names provided in |
rows |
Rows to target
In conjunction with |
height |
Height of icon
The absolute height of the icon in the table cell. By default, this is set
to |
sep |
Separator between icons
In the output of icons within a body cell, |
stroke_color |
Color of the icon stroke/outline
The icon stroke is essentially the outline of the icon. The color of the
stroke can be modified by applying a single color here. If not provided
then the default value of |
stroke_width |
Width of the icon stroke/outline
The |
stroke_alpha |
Transparency value for icon stroke/outline
The level of transparency for the icon stroke can be controlled with a
decimal value between |
fill_color |
Color of the icon fill
The fill color of the icon can be set with |
fill_alpha |
Transparency value for icon fill
The level of transparency for the icon fill can be controlled with a
decimal value between |
vertical_adj |
Vertical adjustment of icon from baseline
The vertical alignment of the icon. By default, a length of |
margin_left |
Margin width left of icon
The length value for the margin that's to the left of the icon can be set
with |
margin_right |
Margin width right of icon
The length value for the margin that's to the right of the icon can be set
with |
a11y |
Accessibility mode for icon
The accessibility mode for the icon display can be set with the |
An object of class gt_tbl
.
fmt_icon()
is compatible with body cells that are of the
"character"
or "factor"
types. Any other types of body cells are ignored
during formatting. This is to say that cells of incompatible data types may
be targeted, but there will be no attempt to format them.
columns
and rows
Targeting of values is done through columns
and additionally by rows
(if
nothing is provided for rows
then entire columns are selected). The
columns
argument allows us to target a subset of cells contained in the
resolved columns. We say resolved because aside from declaring column names
in c()
(with bare column names or names in quotes) we can use
tidyselect-style expressions. This can be as basic as supplying a select
helper like starts_with()
, or, providing a more complex incantation like
where(~ is.numeric(.x) && max(.x, na.rm = TRUE) > 1E6)
which targets numeric columns that have a maximum value greater than
1,000,000 (excluding any NA
s from consideration).
By default all columns and rows are selected (with the everything()
defaults). Cell values that are incompatible with a given formatting function
will be skipped over, like character
values and numeric fmt_*()
functions. So it's safe to select all columns with a particular formatting
function (only those values that can be formatted will be formatted), but,
you may not want that. One strategy is to format the bulk of cell values with
one formatting function and then constrain the columns for later passes with
other types of formatting (the last formatting done to a cell is what you get
in the final output).
Once the columns are targeted, we may also target the rows
within those
columns. This can be done in a variety of ways. If a stub is present, then we
potentially have row identifiers. Those can be used much like column names in
the columns
-targeting scenario. We can use simpler tidyselect-style
expressions (the select helpers should work well here) and we can use quoted
row identifiers in c()
. It's also possible to use row indices (e.g.,
c(3, 5, 6)
) though these index values must correspond to the row numbers of
the input data (the indices won't necessarily match those of rearranged rows
if row groups are present). One more type of expression is possible, an
expression that takes column values (can involve any of the available columns
in the table) and returns a logical vector. This is nice if you want to base
formatting on values in the column or another column, or, you'd like to use a
more complex predicate expression.
from_column()
helper functionfrom_column()
can be used with certain arguments of fmt_icon()
to obtain
varying parameter values from a specified column within the table. This means
that each row could be formatted a little bit differently. These arguments
provide support for from_column()
:
height
sep
stroke_color
stroke_width
stroke_alpha
fill_color
fill_alpha
vertical_adj
margin_left
margin_right
a11y
Please note that for each of the aforementioned arguments, a from_column()
call needs to reference a column that has data of the correct type (this is
different for each argument). Additional columns for parameter values can be
generated with cols_add()
(if not already present). Columns that contain
parameter data can also be hidden from final display with cols_hide()
.
Finally, there is no limitation to how many arguments the from_column()
helper is applied so long as the arguments belong to this closed set.
fmt_icon()
relies on an installation of the fontawesome package to
operate and every icon within that package can be accessed here with either
an icon name or a full name. For example, the Arrow Down icon has an icon
name of "arrow-down"
and its corresponding full name is
"fas fa-arrow-down"
. In most cases you'll want to use the shorter name, but
some icons have both a Solid ("fas"
) and a Regular ("far"
) variant so
only the full name can disambiguate the pairing. In the latest release of
fontawesome (v0.5.2
), there are 2,025 icons and you can view the entire
icon listing by calling info_icons()
. What you'll get from that is an
information table showing every icon and associated set of identifiers.
For this first example of generating icons with fmt_icon()
, let's make a
simple tibble that has two columns of Font Awesome icon names. We separate
multiple icons per cell with commas. By default, the icons are 1 em in
height; we're going to make the icons slightly larger here (so we can see the
fine details of them) by setting height = "4em"
.
dplyr::tibble( animals = c( "hippo", "fish,spider", "mosquito,locust,frog", "dog,cat", "kiwi-bird" ), foods = c( "bowl-rice", "egg,pizza-slice", "burger,lemon,cheese", "carrot,hotdog", "bacon" ) ) |> gt() |> fmt_icon(height = "4em") |> cols_align(align = "center", columns = everything())
Let's take a few rows from the towny
dataset and make it so the
csd_type
column contains Font Awesome icon names (we want only the
"city"
and "house-chimney"
icons here). After using fmt_icon()
to
format the csd_type
column, we get icons that are representative of the two
categories of municipality for this subset of data.
towny |> dplyr::select(name, csd_type, population_2021) |> dplyr::filter(csd_type %in% c("city", "town")) |> dplyr::group_by(csd_type) |> dplyr::slice_max(population_2021, n = 5) |> dplyr::ungroup() |> dplyr::mutate( csd_type = ifelse(csd_type == "town", "house-chimney", "city") ) |> gt() |> fmt_integer() |> fmt_icon(columns = csd_type) |> cols_move_to_start(columns = csd_type) |> cols_label( csd_type = "", name = "City/Town", population_2021 = "Population" )
Let's use a portion of the metro
dataset to create a gt table.
Depending on which train services are offered at the subset of stations,
Font Awesome icon names will be applied to cells where the different
services exist (the specific names are "train-subway"
, "train"
, and
"train-tram"
). With tidyr::unite()
, those icon names can be converged
into a single column (services
) with the NA
values removed. Since the
names correspond to icons and they are in the correct format (separated by
commas), they can be formatted as Font Awesome icons with fmt_icon()
.
metro |> dplyr::select(name, lines, connect_rer, connect_tramway, location) |> dplyr::slice_tail(n = 10) |> dplyr::mutate(lines = "train-subway") |> dplyr::mutate(connect_rer = ifelse(!is.na(connect_rer), "train", NA)) |> dplyr::mutate( connect_tramway = ifelse(!is.na(connect_tramway), "train-tram", NA) ) |> tidyr::unite( col = services, lines:connect_tramway, sep = ",", na.rm = TRUE ) |> gt() |> fmt_icon( columns = services, a11y = "decorative" ) |> cols_merge( columns = c(name, services), pattern = "{1} ({2})" ) |> cols_label( name = "Station", location = "Location" )
Taking a handful of starred reviews from a popular film review website, we
will attempt to format a numerical score (0 to 4) to use the "star"
and
"star-half"
icons. In this case, it is useful to generate the repeating
sequence of icon names (separated by commas) in the rating
column before
introducing the table to gt()
. We can make use of the numerical rating
values in stars
within fmt_icon()
with a little help from
from_column()
. Using that, we can dynamically adjust the icon's
fill_alpha
(i.e., opacity) value and accentuate the films with higher
scores.
dplyr::tibble( film = c( "The Passengers of the Night", "Serena", "The Father", "Roma", "The Handmaiden", "Violet", "Vice" ), stars = c(3, 1, 3.5, 4, 4, 2.5, 1.5) ) |> dplyr::mutate(rating = dplyr::case_when( stars %% 1 == 0 ~ strrep("star,", stars), stars %% 1 != 0 ~ paste0(strrep("star,", floor(stars)), "star-half") )) |> gt() |> fmt_icon( columns = rating, fill_color = "red", fill_alpha = from_column("stars", fn = function(x) x / 4) ) |> cols_hide(columns = stars) |> tab_source_note( source_note = md( "Data obtained from <https://www.rogerebert.com/reviews>." ) )
A fairly common thing to do with icons in tables is to indicate whether
a quantity is either higher or lower than another. Up and down arrow symbols
can serve as good visual indicators for this purpose. We can make use of the
"up-arrow"
and "down-arrow"
icons here. The fmt_icon()
function has to
find those text values in cells to generate the icons, so, lets generate the
text within a new column with cols_add()
(an expression is used therein to
generate the correct text given the close
and open
values). Following
that, fmt_icon()
is used and its fill_color
argument is provided with a
named vector that indicates which color should be used for each icon.
sp500 |> dplyr::slice_head(n = 10) |> dplyr::select(date, open, close) |> dplyr::arrange(-dplyr::row_number()) |> gt(rowname_col = "date") |> cols_add(week = date, .after = date) |> cols_add(dir = ifelse(close > open, "arrow-up", "arrow-down")) |> cols_merge(columns = c(date, week), pattern = "{1} ({2})") |> fmt_date(columns = date, date_style = "m_day_year") |> fmt_datetime(columns = week, format = "w", pattern = "W{x}") |> fmt_currency() |> fmt_icon( columns = dir, fill_color = c("arrow-up" = "green", "arrow-down" = "red") ) |> cols_label( open = "Opening Value", close = "Closing Value", dir = "" ) |> opt_stylize(style = 1, color = "gray")
3-26
v0.10.0
(October 7, 2023)
Other data formatting functions:
data_color()
,
fmt()
,
fmt_auto()
,
fmt_bins()
,
fmt_bytes()
,
fmt_chem()
,
fmt_country()
,
fmt_currency()
,
fmt_date()
,
fmt_datetime()
,
fmt_duration()
,
fmt_email()
,
fmt_engineering()
,
fmt_flag()
,
fmt_fraction()
,
fmt_image()
,
fmt_index()
,
fmt_integer()
,
fmt_markdown()
,
fmt_number()
,
fmt_partsper()
,
fmt_passthrough()
,
fmt_percent()
,
fmt_roman()
,
fmt_scientific()
,
fmt_spelled_num()
,
fmt_tf()
,
fmt_time()
,
fmt_units()
,
fmt_url()
,
sub_large_vals()
,
sub_missing()
,
sub_small_vals()
,
sub_values()
,
sub_zero()
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.