renkun-ken / formattable

Formattable Data Structures
Other
695 stars 78 forks source link

[Suggestion] Three colour gradient: compute colours through the `scales` package #61

Open zeehio opened 8 years ago

zeehio commented 8 years ago

Hi, nice work on the package!

I recently discovered your package. I have a similar package named condformat with much less features (I can only change background gradients) but with PDF output in knitr.

Looking at your source code, I found that you compute the gradient colours with the normalize function. While I was working on my package I found really useful the set of gradients used in ggplot2, that are created using the scales package. It offers easy to build color scales:

# Three colour gradient
library(scales)
data_vector <- c(-10, -4, -2, -1, 1, 4, 10)
# Create palette: A gradient going from red to blue through white:
colour_scale <- scales::div_gradient_pal(low = "red", mid = "white", high = "blue")
# Rescale data:
scaled_data <- scales::rescale_mid(data, mid = 0)
# Apply colour scale to scaled data:
data_colours <- colour_scale(scaled_data)
# Print colour names:
print(data_colours)
# [1] "#FF0000" "#FFB29A" "#FFD9CB" "#FFECE5" "#F1E7FF" "#C4A2FF" "#0000FF"

The default palettes and options are well chosen, for instance they offer palettes for colorblind people (through the dichromat_pal function).

Feel free to use it, if you like it. It saved me a lot of work and I feel it provides a well thought interface.

marceluk commented 8 years ago

Hi zeehio,

In order for your example to work correctly I wonder if your line...

# Rescale data:
scaled_data <- scales::rescale_mid(data, mid = 0)

should read...

# Rescale data:
scaled_data <- scales::rescale_mid(data_vector, mid = 0)

ie. replace data with data_vector

zeehio commented 8 years ago

Yes, sorry!