能否在formattable::color_tile函数中使用两种以上颜色?
Great question! The built-in color_tile() function in formattable only lets you specify two endpoint colors, which leads to that muddy brown middle you're seeing when pairing red and springgreen. But don't worry—we can absolutely create a solution that gives you that smooth red-amber-green gradient you want. Here are two solid approaches:
1. Build a custom three-color tile formatter
The most reliable way is to extend the logic of color_tile() using the scales package's multi-color gradient tools. This lets you explicitly define three (or more) stop colors for the transition:
library(formattable) library(scales) # Custom formatter for three-color gradient tiles color_tile_3 <- function(colors = c("red", "goldenrod", "springgreen")) { formatter("span", style = function(x) { # Normalize values to a 0-1 range x_normalized <- (x - min(x, na.rm = TRUE)) / (max(x, na.rm = TRUE) - min(x, na.rm = TRUE)) # Get the corresponding color from the three-stop gradient fill_color <- gradient_n_pal(colors)(x_normalized) # Apply the tile styling (matches color_tile's default look) paste0("display: block; padding: 0 4px; border-radius: 4px; background-color: ", fill_color, ";") }) }
Test it with sample data:
# Example data frame test_df <- data.frame( Metric = c("A", "B", "C", "D", "E", "F"), Score = c(-2.5, -1, 0, 1, 2, 3) ) # Apply the custom formatter formattable(test_df, list( Score = color_tile_3() ))
This will give you a clean transition from red (lowest values) → amber (mid values) → springgreen (highest values), no muddy brown in sight.
2. Hack the two-color gradient for better mid-tones
If you prefer not to write a custom function, you can tweak your color choices to make the two-color gradient's midpoint lean closer to amber. Use HSL color values to ensure the transition stays in the warm-to-green spectrum:
# Use HSL-defined red and green to shift the mid-tone to amber formattable(test_df, list( Score = color_tile(hsl(0, 1, 0.5), hsl(120, 1, 0.5)) ))
This is a quick fix, but it's less flexible than the custom three-color approach—you can't explicitly control the exact midpoint color.
Bonus tip
You can customize the colors parameter in color_tile_3() to use any hex codes or named colors you want. For example, to use a brighter amber:
color_tile_3(colors = c("#ff3333", "#ffcc00", "#33cc33"))
If you want the gradient to center around a specific value (like 0) instead of the min/max, adjust the normalization step in the custom function to anchor around that midpoint.
内容的提问来源于stack exchange,提问作者henrygd

