-
Notifications
You must be signed in to change notification settings - Fork 0
/
tablesWithIcons.Rmd
264 lines (204 loc) · 8.97 KB
/
tablesWithIcons.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
---
title: "Pretty tables"
date: "`r Sys.Date()`"
output:
#github_document:
html_document:
# keep_md: true
highlight: pygments
depth: 4
number_sections: no
theme: sandstone
toc: yes
toc_float:
collapsed: yes
smooth_scroll: yes
---
```{r setup, include=FALSE}
here::i_am("tablesWithIcons.Rmd")
knitr::opts_chunk$set(tidy=FALSE,
echo = TRUE,
cache = FALSE,
message=FALSE,
warning=FALSE,
fig.align='center',
fig.width = 16,
fig.path = "figures/")
knitr::opts_knit$set(progress = TRUE, verbose = TRUE)
library(knitr)
library(tidyverse)
library(magick)
library(here)
library(gt)
```
<style type="text/css">
body{
font: 14px "Mina", sans-serif;
}
</style>
This is a short practice on making pretty tables using the gt package with icons that can be downloaded and lightly edited with the Magick package or customized in illustrator. Additionally, we can also do a simple shiny app to make tables with a given icon for every cell in a table.
****
<br />
## Example of icons inside the table
Using a test data set with binary data like the plants traits data set from the cluster package.
* Sample 10 observations and five traits
```{r}
data0 <- cluster::plantTraits %>%
sample_n(10) %>%
select(lign, leafy, suman, everalw, windgl)
```
<br />
Could use library Icons but would prefer to use google icons (https://fonts.google.com/icons) and this is not working (https://github.com/mitchelloharawild/icons/issues/70). So picked the icons on the website and use R to download them.
* Prepare table with download links and saving path to extract icons. Save icons with matching name with data.
```{r, eval = FALSE}
dir.create(here('elements'), showWarnings = FALSE)
urls <- 'https://fonts.gstatic.com/s/i/short-term/release/materialsymbolsoutlined/'
icons <- data.frame(urls=paste0(urls, c("check_circle","cancel"),"/default/48px.svg"),
svgs = here('elements', paste0(c("1","0"),".svg")),
code = c("Present","Absent"))
walk2(icons$urls, icons$svgs, safely(~ download.file(.x , .y, mode = "wb")))
```
<br />
* Edit icons to have different colors with the package Magick, and to make an empty icon for missing data.
```{r, eval = FALSE}
present <- image_colorize(image_read_svg(icons$svgs[1]), 100, '#93c47d')
absent <- image_colorize(image_read_svg(icons$svgs[2]), 100, '#EA9999')
image_write(present, path = icons$svgs[1], format = "svg")
image_write(absent, path = icons$svgs[2], format = "svg")
image_write(image_colorize(present, 100, 'white'),
path = here('elements',"NA.svg"), format = "svg")
## show colored icons
image_append(c(present, absent))
```
<br />
* Replace the data by the icons paths.
```{r}
icons <- data.frame(icons = list.files(here('elements'), full.names = TRUE, pattern = '.svg')) %>%
mutate(value = basename(tools::file_path_sans_ext(icons)))
data <- data0 %>%
rownames_to_column('Species') %>%
pivot_longer(-Species, values_ptypes = as.character()) %>%
replace_na(list(value = "NA")) %>%
left_join(icons, by = 'value') %>%
select(-value) %>%
pivot_wider(names_from = name, values_from = icons)
```
<br />
* Use the gt package to include icons while making table.
```{r, fig.align='center', out.width = "300px"}
qr <- gt(data) %>%
tab_header(
title = md("Subsample of plants traits dataset")) %>%
opt_table_font(font = list(google_font("Mina"), default_fonts())) %>%
cols_label(lign = 'Woody plant', leafy = 'Leafy plant',
suman = 'Summer annual',everalw = 'Leaves always evergreen',
windgl = 'Wind dispersed fruits') %>%
text_transform(locations = cells_body(columns = 2:ncol(data),
rows = everything()),
fn = function(x) { map_chr(x, ~ local_image(filename = .x,
height = 40))}) %>%
tab_source_note(
source_note =
md("**Source:** Data from plantTraits of the Cluster package.")) %>%
cols_align(
align = "center",
columns = everything()) %>%
cols_width(everything() ~ px(120)) %>%
tab_style(style = list(cell_text(weight = "bold")),
locations = list(cells_body(columns = Species,
rows = everything()),
cells_column_labels(columns = everything()))) %>%
tab_options(data_row.padding = px(0),
data_row.padding.horizontal = px(0),
table.font.size = px(20),
heading.align = 'center',
table.border.top.style = "hidden",
table.border.bottom.style = "hidden",
table_body.hlines.style = "hidden",
table.background.color = "#FFFFFF00")
gtsave(qr, "figures/fig1.png")
include_graphics("figures/fig1.png")
```
<br />
This Rmarkdown is both being knit as an html and for github, and since for the latter this doesn't render the image with gt but lines of html code it's then easier to save the image and then show the locally saved image.
****
<br />
## Example of table with all elements as icons
* Make customized images for each element in illustrator (elementsToExport.ai). Name the files differently depending if these are column names, row names or content.
* Replacing all elements as icons requires some data wrangling given the transforming function doesn't work for column names
```{r}
icons <- data.frame(icons = list.files(here('elements'), full.names = TRUE,
pattern = '.svg')) %>%
mutate(columns = basename(tools::file_path_sans_ext(icons))) %>%
filter(str_detect(columns, "_")) %>%
separate(columns, into = c("column","content"), sep = "_", extra = "drop")
# prepare column header
colData <- data.frame(content = c('Species',colnames(data0))) %>%
left_join(filter(icons, column %in% 'header'), by = "content") %>%
pivot_wider(names_from = content, values_from = icons) %>%
select(-column)
# prepare row header
rowData <- data.frame(content = as.character(seq(1:nrow(data0)))) %>%
left_join(filter(icons, column %in% 'Species'), by = "content") %>%
rename(Species = icons) %>%
select(-column, -content)
# prepare content
data1 <- data0 %>%
mutate(row = row_number()) %>%
pivot_longer(cols = -row, names_to = "column", values_to = "content",
values_ptypes = as.character()) %>%
replace_na(list(content = "NA")) %>%
left_join(select(filter(icons, column %in% 'content'),-column),
by = 'content') %>%
pivot_wider(id_cols = row, names_from = column, values_from = icons) %>%
select(-row)
dataIcons <- colData %>%
bind_rows(cbind(rowData, data1))
```
<br />
* Use the gt package to include icons while making table.
```{r, fig.align='center', out.width = "300px"}
qr2 <- gt(dataIcons) %>%
tab_header(
title = md("Subsample of plants traits dataset")) %>%
opt_table_font(font = list(google_font("Mina"), default_fonts())) %>%
text_transform(locations = cells_body(columns = everything(),
rows = everything()),
fn = function(x) { map_chr(x, ~ local_image(filename = .x,
height = 100))}) %>%
tab_source_note(
source_note =
md("**Source:** Data from plantTraits of the Cluster package.")) %>%
cols_align(
align = "center",
columns = everything()) %>%
tab_options(
data_row.padding = px(0),
data_row.padding.horizontal = px(4),
table.font.size = px(35),
heading.align = 'center',
column_labels.hidden = TRUE, ## remove header without icons paths
table.border.top.style = "hidden",
table.border.bottom.style = "hidden",
table_body.hlines.style = "hidden")
gtsave(qr2, "figures/fig2.png")
include_graphics("figures/fig2.png")
```
<br />
The gt approach to include images in a table still could be better because it's hard to adjust the height of the elements in a way the data_row padding is not too weird. The proportions of the icons dictates the padding given the height provided to the local_image function.
****
<br />
## Example of a shiny table to replace every cell for a given customized icon
A major limitation of shiny is how to share the app without having to deploy it in shinyapps.io or without having to install the same R package versions to run it. For a workaround of this problem we can use binder that will open the app in a similar environment it was developed.
The shiny app is in the [shiny_app](https://github.com/acafonsosilva/R_tables_graphicExamples/blob/main/shiny_app/app.R) folder. It can be run with the following code assuming the environment has all the required packages
```{r, eval = FALSE}
library(shiny)
shinyAppDir(
here("shiny_app"),
options = list(height = 900)
)
```
****
### Shiny app code
```{r, code = readLines(here("shiny_app/app.R"))}
```