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".
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.
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().
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, let’s 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.