hughjonesd / huxtable

An R package to create styled tables in multiple output formats, with a friendly, modern interface.
http://hughjonesd.github.io/huxtable
Other
321 stars 28 forks source link

Color cells by a continuous scale #51

Closed michael-herman closed 6 years ago

michael-herman commented 6 years ago

I'd like to color the text or shade the background of cells in a column, from green to red, by either rank or the values in the cells themselves. What I'm trying to do is similar to ggplot2's function aes(color = continuous_var).

In the huxtable documentation, I can see how to specify the color of a text conditionally (e.g. set_text_color(ht, where(ht == 1), 'blue')). But I haven't been able to specify a range.

Maybe this is in the documentation and I missed it (if so, please let me know). If not, can this functionality be added to future versions of huxtable?

hughjonesd commented 6 years ago

It's an interesting idea and I've seen similar stuff in e.g. the formattable package. I'm not sure that the use case is sufficiently common to add a function, but I am open to being convinced. Meanwhile I'd suggest a for loop.

michael-herman commented 6 years ago

Thank you!

I’ll check out formattable and see if that will suffice.

For some context (and to sell the feature a little), I work as an analyst for a large insurance company and have been trying to switch some processes to R (in some cases from Excel-driven processes). A lot of senior management like tables in Excel that shade cells from green to red by the value of the cell. It helps identify the extremes quickly. Not having this feature is no small complaint for the consumers of these reports. While this feature may seem trivial in some instances, it is the kind of thing that would help proliferate adopting R in a business context, at least in my opinion.

I love the package though, and I think you’ve done a remarkable job. Hats off.

hughjonesd commented 6 years ago

OK, I think this is reasonable and I'll leave it open. Pull requests welcome.

hughjonesd commented 6 years ago

For reference, here is an ugly but simple way to do this:

ht <- huxtable(a = 1:3, b = 3:1)
set_background_color(ht, c("red", "blue", "green") [unlist(ht)])

Or for continuous variables, e.g.:

ht <- huxtable(a = rnorm(3), b = rnorm(3))
colors <- c("red", "blue", "green")[ Hmisc::cut2(unlist(ht), g = 3) ]
set_background_color(ht, colors)
hughjonesd commented 6 years ago

See by_colorscale, map_background_color and friends in master.