Reputation: 1165
Is it possible to color-code a table (generated with huxtable) through the colors given in a different table?
head_mtcars <- head(mtcars)
tbl_A <- as_hux(head_mtcars[1:2])
tbl_B <- as_hux(head_mtcars[3:4])
1) As a start, I would like to colorize the elements in column 1 and 2 of tbl_A
by a colorspace for each column respectively
tbl_A %>%
huxtable::add_colnames() %>%
map_background_color("for each column of tbl_A", by_colorspace("orange", "white", "green"))
2) Next, I would like to colorize the elements in column 1 and 2 of tbl_A
by a colorspace for each column of tbl_B,
i.e., the elements in col 1 of table tbl_A
by tbl_B[,1]
and the elements in col 2 of table tbl_A
by tbl_B[,2]
tbl_A %>%
huxtable::add_colnames() %>%
map_background_color("for each column of tbl_B", by_colorspace("orange", "white", "green"))
3) Finally, not by column but for a whole table: colorize elements in ht by the values of ht2:
ht <- as_hux(matrix(rnorm(25), 5, 5))
ht2 <- as_hux(matrix(rnorm(25), 5, 5))
map_background_color(ht, by_colorspace("orange", "white", "green"))
Many thanks for any help!
Upvotes: 0
Views: 98
Reputation: 2262
Part A: to apply colourspaces by column, you have to specify them separately:
tbl_A %>%
map_background_color(everywhere, 1, by_colorspace("orange", "white", "green")) %>%
map_background_color(everywhere, 2, by_colorspace("orange", "white", "green")) %>%
huxtable::add_colnames()
This might be a feature request because I can imagine doing it by column is a common use case.
Part B: I think doing this "manually" is going to be simplest - i.e. construct the colours you want and then use them in set_background_color
. We can use huxtable's by_colorspace
outside of a map_
call, like this. Again, done separately by columns:
# this is hairy. Details in ?"huxtable::mapping-functions"
colors1 <- by_colorspace("orange", "white", "green")(tbl_B, 1:6, 1,
matrix(NA, 6, 1))
colors2 <- by_colorspace("orange", "white", "green")(tbl_B, 1:6, 2,
matrix(NA, 6, 1))
tbl_A %>%
set_background_color(everywhere, 1:2, cbind(colors1, colors2)) %>%
huxtable::add_colnames()
Part C, so, the colour mapping is not done within individual columns, but over the whole table:
colors_all <- by_colorspace("orange", "white", "green")(tbl_B, 1:6, 1:2,
matrix(NA, 6, 2))
tbl_A %>%
set_background_color(everywhere, 1:2, colors_all) %>%
huxtable::add_colnames()
Update. In github master, which will probably become huxtable 4.8.0, you can indeed now do:
tbl_A %>%
map_background_color(everywhere, 1:2,
by_colorspace("orange", "white", "green", colwise = TRUE))
rather than calling map_...
for each column separately.
Upvotes: 1