Every exported function appears below, with a runnable example.
Gradients are shown with previewGradient(), which is part
of the package; discrete colours use one small helper,
swatch().
swatch <- function(colors, title = NULL) {
df <- data.frame(i = seq_along(colors), fill = colors)
discrete <- length(colors) <= 24
ggplot(df, aes(i, 1, fill = fill)) +
geom_tile(colour = if (discrete) "white" else NA,
linewidth = if (discrete) 1.5 else 0) +
scale_fill_identity() +
labs(title = title, x = NULL, y = NULL) +
theme_void(base_size = 9) +
theme(plot.title = element_text(size = 9, hjust = 0))
}A specification describes a gradient without reference to any data, so the same object works on any range.
gradientParams()The main constructor.
p <- gradientParams(
colors = c("navy", "white", "firebrick"),
midpoints = 0.5,
center = 0.5,
width = 0.3
)
p
#> <brouillet gradient>
#> mode: sigmoid
#> colors: navy -> white -> firebrick
#> space: Lab (linear)
#> resolution: 100
#> midpoints: 0.5
#> curve: center 0.5, width 0.3midpoints places the colour stops as fractions of the
range; center/width/asymmetry
shape the curve inside each segment. The remaining arguments are
below.
gradient.modeThree families. "sigmoid" is the contrast curve,
"linear" the same vocabulary with straight lines,
"custom" your own mapping.fun applied once
across the whole colour list.
pal <- c("navy", "white", "firebrick")
previewGradient(gradientParams(pal, midpoints = 0.5, gradient.mode = "linear")) +
labs(title = 'gradient.mode = "linear"') +
previewGradient(gradientParams(pal, midpoints = 0.5, gradient.mode = "sigmoid",
width = 0.3)) +
labs(title = 'gradient.mode = "sigmoid", width = 0.3') +
previewGradient(gradientParams(pal, gradient.mode = "custom",
mapping.fun = function(x) x^2)) +
labs(title = 'gradient.mode = "custom", mapping.fun = x^2') +
patchwork::plot_layout(ncol = 1)In linear mode width still applies: 1 is a
plain ramp, below 1 leaves flat regions at the ends.
previewGradient(gradientParams(pal, midpoints = 0.5, gradient.mode = "linear",
width = 0.5)) +
labs(title = 'linear with width = 0.5')The clip colours are plain arguments; no extra call is needed.
previewGradient(
gradientParams(pal, midpoints = 0.5, width = 0.3,
low.clip.color = "grey35", high.clip.color = "gold",
blend.clip = FALSE),
limits = c(-2, 2)
) + labs(title = "clip colours set on gradientParams()")space and interpolate"Lab" is perceptual and matches what
ggplot2 does internally; "sRGB" is the pre-0.2
behaviour. interpolate chooses straight lines or a spline
between stops.
previewGradient(gradientParams(c("navy", "white"), space = "Lab")) +
labs(title = 'space = "Lab"') +
previewGradient(gradientParams(c("navy", "white"), space = "sRGB")) +
labs(title = 'space = "sRGB"') +
previewGradient(gradientParams(pal, midpoints = 0.5, interpolate = "spline")) +
labs(title = 'interpolate = "spline"') +
patchwork::plot_layout(ncol = 1)rescaleWith TRUE the curve is stretched so the end colours are
reached exactly. With FALSE it is used as-is, so a sigmoid
approaches the ends without arriving.
gradientTemplate()The same arguments without colors: a shape waiting for a
palette. Useful when the curve is a house style but the colours change
per figure.
house <- gradientTemplate(width = 0.25, high.clip.color = "gold")
house
#> <brouillet gradient template> (no colours yet)
#> mode: sigmoid
#> space: Lab (linear)
#> curve: center 0.5, width 0.25
#> clipping: none | gold
#> complete it with withColors(x, colors)A template cannot be plotted until it has colours; every converter refuses it with a message saying so.
withColors()Completes a template, or swaps the palette of a finished specification.
withColors(house, c("black", "orange"))
#> <brouillet gradient>
#> mode: sigmoid
#> colors: black -> orange
#> space: Lab (linear)
#> resolution: 100
#> curve: center 0.5, width 0.25
#> clipping: none | gold
withColors(p, c("grey90", "darkgreen"))$colors
#> [1] "grey90" "darkgreen"previewGradient(withColors(house, c("black", "orange"))) +
labs(title = "the house curve, a new palette")updateGradient()Changes fields and revalidates. NULL resets a field to
its default.
updateGradient(p, width = 0.1)$width
#> [1] 0.1
updateGradient(p, high.clip.color = "gold")$high.clip.color
#> [1] "gold"
updateGradient(p, high.clip.color = NULL)$high.clip.color
#> NULL
tryCatch(updateGradient(p, widht = 0.1), error = function(e) conditionMessage(e))
#> [1] "Unknown gradient field(s): widht. Valid fields are: colors, midpoints, center, width, asymmetry, resolution, space, interpolate, rescale, low.clip.color, high.clip.color, blend.clip, gradient.mode, mapping.fun, curve.fun, steepness.preset."Changing the palette length drops stale midpoints rather than failing:
reverseGradient()Mirrors a specification: colours, midpoints, center and
asymmetry all flip, and the clip colours swap. Reversing
twice is the identity.
asym <- gradientParams(c("navy", "white", "firebrick"), midpoints = 0.4,
center = 0.3, asymmetry = 0.5)
rev_asym <- reverseGradient(asym)
c(midpoints = rev_asym$midpoints, center = rev_asym$center,
asymmetry = rev_asym$asymmetry)
#> midpoints center asymmetry
#> 0.6 0.7 -0.5previewGradient(asym) + labs(title = "original") +
previewGradient(rev_asym) + labs(title = "reversed") +
patchwork::plot_layout(ncol = 1)contrastCurve()The S-shaped mapping from position-in-data to position-in-ramp.
center is the 50% point, width the span from
5% to 95%, asymmetry which side rolls off slowly.
x <- seq(0, 1, length.out = 20001)
y <- contrastCurve(x, center = 0.7, width = 0.2)
x[which(y >= 0.5)[1]]
#> [1] 0.7
x[which(y >= 0.95)[1]] - x[which(y >= 0.05)[1]]
#> [1] 0.19995curves <- do.call(rbind, lapply(
list(c(0.5, 1.0, 0), c(0.5, 0.4, 0), c(0.5, 0.12, 0),
c(0.5, 0.4, 0.8), c(0.3, 0.4, 0)),
function(k) data.frame(x = x, y = contrastCurve(x, k[1], k[2], k[3]),
setting = sprintf("center %.2g, width %.2g, asym %.1f",
k[1], k[2], k[3]))
))
ggplot(curves, aes(x, y, colour = setting)) +
geom_abline(slope = 1, intercept = 0, linetype = 3, colour = "grey70") +
geom_line() +
labs(x = "position in data", y = "position in ramp", colour = NULL) +
theme_minimal(base_size = 9) +
theme(legend.position = "right")doubleSigmoid()A four-parameter curve: the product of two logistic factors, and the
mapping brouillet used before 0.2. Because the factors multiply, the
curve stays near zero until the later inflexion point, then
jumps to whatever level the earlier factor has reached and continues
gradually – a hard threshold followed by a slow ramp, ending short of 1.
contrastCurve() cannot do that: it is continuous at its
centre and is rescaled to reach both ends.
f <- doubleSigmoid(sigma1 = 200, sigma2 = 200,
inflexpoint1 = 0.3, inflexpoint2 = 0.4)
round(f(seq(0, 1, 0.25)), 3)
#> [1] 0.022 0.140 0.455 0.771 0.925
threshold <- doubleSigmoid(sigma1 = 500, sigma2 = 5,
inflexpoint1 = 0.3, inflexpoint2 = 0.6)
round(threshold(seq(0, 1, 0.1)), 2)
#> [1] 0.00 0.00 0.00 0.00 0.00 0.00 0.32 0.69 0.73 0.77 0.80previewGradient(gradientParams(c("navy", "firebrick"), curve.fun = threshold)) +
labs(title = "doubleSigmoid(500, 5, 0.3, 0.6): nothing, then a jump, then a ramp")Two sharp factors give a single step at the later inflexion point rather than two steps, since multiplying two rising curves acts as an AND. Note also that the result is not rescaled, so the end colours are approached rather than reached.
curve.funAny function from [0, 1] to [0, 1] can replace the built-in curve. It
applies within each segment, unlike
mapping.fun, which applies once across the whole colour
list.
previewGradient(gradientParams(c("navy", "white", "firebrick"), midpoints = 0.5,
curve.fun = function(u) u^3)) +
labs(title = "curve.fun = u^3, applied in both segments")steepnessPresets() and
steepness.presetThe named curve shapes from the pre-0.2 API. Each row carries both
parameterisations: the original sigma pair, and the
center/width/ asymmetry that
reproduce the same shape in the modern curve.
steepnessPresets()
#> preset sigma1 sigma2 center width asymmetry
#> 1 very_low 500 500 0.56 0.87 -0.10
#> 2 lower 350 350 0.55 0.85 -0.08
#> 3 low 200 200 0.51 0.76 0.02
#> 4 low_longtail 500 200 0.53 0.82 -0.02
#> 5 medium 100 100 0.45 0.49 0.12
#> 6 medium_longtail 500 200 0.53 0.82 -0.02
#> 7 high 50 50 0.41 0.26 0.10
#> 8 very_high 25 25 0.40 0.14 0.04
#> 9 extreme 5 5 0.40 0.03 0.00
#> 10 extreme_longtail 500 5 0.40 0.49 0.93gradientParams() takes the names directly as a
shorthand:
gradientParams(c("navy", "firebrick"), steepness.preset = "high")
#> <brouillet gradient>
#> mode: sigmoid
#> colors: navy -> firebrick
#> space: Lab (linear)
#> resolution: 100
#> curve: high (center 0.41, width 0.26, asymmetry 0.1)Anything you give explicitly wins, so a preset is a starting point:
previewGradient(gradientParams(c("navy", "firebrick"), steepness.preset = "very_low")) +
labs(title = "very_low") +
previewGradient(gradientParams(c("navy", "firebrick"), steepness.preset = "medium")) +
labs(title = "medium") +
previewGradient(gradientParams(c("navy", "firebrick"), steepness.preset = "extreme")) +
labs(title = "extreme") +
patchwork::plot_layout(ncol = 1)A preset gives the old shape, not the old colours: the
modern curve interpolates in Lab and is rescaled to reach both end
colours, so the result differs from
gradient_params(steepness_preset =) by between about 1 and
50 RGB units depending on the preset. Use gradient_params()
when you need the old rendering exactly.
Out-of-range values take their own colours, shown as bands on the colourbar.
clipped <- gradientParams(c("navy", "white", "firebrick"), midpoints = 0.5,
width = 0.3,
low.clip.color = "grey35", high.clip.color = "gold")
asColorFun(clipped, limits = c(-2, 2))(c(-99, -2, 0, 2, 99, NA))
#> [1] "grey35" "#000080" "#FFFFFF" "#B22222" "gold" "grey95"previewGradient(clipped, limits = c(-2, 2)) +
labs(title = "the clip colours appear as bands beyond the limits")blend.clip = TRUE fades the clip colour in over the
first 10% beyond each limit instead of switching abruptly:
previewGradient(updateGradient(clipped, blend.clip = TRUE), limits = c(-2, 2)) +
labs(title = "blend.clip = TRUE")clippingGradient()Given a specification, it sets the clip colours and hands back a specification:
clippingGradient(gradientParams(c("navy", "firebrick")),
low.clip.color = "grey35", high.clip.color = "gold")
#> <brouillet gradient>
#> mode: sigmoid
#> colors: navy -> firebrick
#> space: Lab (linear)
#> resolution: 100
#> curve: center 0.5, width 0.4
#> clipping: grey35 | goldGiven a stop table instead, it restricts the table to a window and appends one stop just outside each end.
asColorFun()A vectorised value-to-colour function, interface-compatible with
circlize::colorRamp2(), so it drives ComplexHeatmap, base
graphics and raster export as well as ggplot2.
col_fun <- asColorFun(p, limits = c(-2, 2), na.color = "grey90")
col_fun(c(-2, -1, 0, 1, 2))
#> [1] "#000080" "#947BC0" "#FFFFFF" "#E49689" "#B22222"
col_fun(c(-99, 99, NA))
#> [1] "#000080" "#B22222" "grey90"asScaleFillGradient() and
asScaleColorGradient()ggplot2 scales. show.clip puts the clip colours on the
colourbar, clip.width sets their width as a proportion of
the range, na.value colours missing data,
guide is passed through, and ... reaches
scale_*_gradientn().
set.seed(1)
grid <- expand.grid(x = seq(0, 1, length.out = 60), y = seq(0, 1, length.out = 60))
grid$z <- with(grid, 2.4 * sin(2.1 * pi * x) * cos(1.6 * pi * y))
ggplot(grid, aes(x, y, fill = z)) +
geom_raster() +
asScaleFillGradient(clipped, limits = c(-2, 2)) +
coord_cartesian(expand = FALSE) +
theme_minimal(base_size = 9)ggplot(grid, aes(x, y, fill = z)) +
geom_raster() +
asScaleFillGradient(clipped, limits = c(-2, 2), na.value = "black",
guide = guide_colourbar(barheight = 6),
show.clip = TRUE, clip.width = 0.06) +
coord_cartesian(expand = FALSE) +
theme_minimal(base_size = 9)ggplot(mtcars, aes(wt, mpg, colour = qsec)) +
geom_point(size = 3) +
asScaleColorGradient(p, limits = range(mtcars$qsec)) +
theme_minimal(base_size = 9)buildGradient()Materialises a specification as a table of stops.
previewGradient()Renders a specification as a band, for checking it before committing it to a figure.
n.ticks sets the axis ticks; clip.pad how
far past the limits to draw so the clipped regions are visible, and
0 keeps the preview inside the limits.
These skip the specification object and return a stop table. They
take the curve arguments plus low.value and
high.value in data units.
sigmoidGradient2(), sigmoidGradient3(),
sigmoidGradientn()g2 <- sigmoidGradient2("navy", "firebrick", center = 0.7, width = 0.15)
g3 <- sigmoidGradient3("navy", "firebrick", "white", midpoint.value = 0.25)
gn <- sigmoidGradientn(c("black", "navy", "white", "firebrick", "gold"),
midpoints = c(0.2, 0.5, 0.75), width = 0.3)
swatch(g2$color, "sigmoidGradient2(center = 0.7, width = 0.15)") /
swatch(g3$color, "sigmoidGradient3(midpoint.value = 0.25)") /
swatch(gn$color, "sigmoidGradientn(midpoints = c(0.2, 0.5, 0.75))")sigmoidGradient3() takes midpoint.value in
data units, unlike midpoints elsewhere, because it is a
direct builder rather than a specification.
linearGradient2() and
linearGradientn()Straight lines instead of logistics, same vocabulary.
width = 1 is an ordinary ramp; width < 1
leaves flat regions at both ends.
l2 <- linearGradient2("navy", "firebrick")
l2f <- linearGradient2("navy", "firebrick", width = 0.5)
swatch(l2$color, "linearGradient2() -- plain ramp") /
swatch(l2f$color, "linearGradient2(width = 0.5) -- flat ends")customGradientFun()Your own mapping, applied once across the whole colour list.
sq <- customGradientFun(c("white", "navy"), mapping.fun = function(x) x^2)
st <- customGradientFun(c("white", "navy"), mapping.fun = function(x) floor(x * 4) / 4)
swatch(sq$color, "mapping.fun = x^2") /
swatch(st$color, "mapping.fun = floor(x * 4) / 4 -- four bands")A useful case is histogram equalisation, where each quantile of the data gets an equal share of the colour range:
equalise <- function(values, limits) {
f <- stats::ecdf(values)
lo <- f(limits[1]); hi <- f(limits[2])
function(x) {
y <- f(limits[1] + x * (limits[2] - limits[1]))
if (hi > lo) (y - lo) / (hi - lo) else y
}
}
skewed <- rlnorm(4000)
lims <- c(0, unname(quantile(skewed, 0.99)))
eq <- gradientParams(c("white", "navy"), gradient.mode = "custom",
mapping.fun = equalise(skewed, lims))
asColorFun(eq, limits = lims)(unname(quantile(skewed, c(0.1, 0.5, 0.9))))
#> [1] "#EAE3F2" "#937ABF" "#30198C"brouillet does not design palettes, and does not try to.
colorspace, viridisLite,
RColorBrewer, scico and the rest have spent
years on that problem. They supply the paint; brouillet decides how it
goes on: where along the data range the colours change, and what happens
past the ends.
Any palette that returns a character vector of colours is a valid
colors argument. Interior stops default to evenly spaced,
so a five-colour palette needs nothing else.
pal <- viridisLite::viridis(5)
previewGradient(gradientParams(pal, width = 1, gradient.mode = "linear")) +
labs(title = "viridis as it comes") +
previewGradient(gradientParams(pal, width = 0.3)) +
labs(title = "the same palette, contrast curve at width = 0.3") +
patchwork::plot_layout(ncol = 1)The curve redistributes an existing palette rather than altering its colours: the stops are untouched, only the positions where they land move.
asColorFun(gradientParams(viridisLite::viridis(5), width = 0.3))(c(0, 1))
#> [1] "#440154" "#FDE725"colorspace is useful twice over here: once for the
palette, once for deriving out-of-range colours that still belong to
it.
div <- colorspace::divergingx_hcl(5, "RdBu")
spec <- gradientParams(
div,
width = 0.35,
low.clip.color = colorspace::darken(div[1], 0.4),
high.clip.color = colorspace::darken(div[5], 0.4)
)
previewGradient(spec, limits = c(-2, 2)) +
labs(title = "divergingx_hcl, sharpened, with darkened clip colours")A template is the natural way to keep a house curve and vary the paint.
house <- gradientTemplate(width = 0.3, high.clip.color = "black")
previewGradient(withColors(house, RColorBrewer::brewer.pal(5, "PuOr"))) +
labs(title = "RColorBrewer PuOr") +
previewGradient(withColors(house, colorspace::sequential_hcl(5, "Plasma"))) +
labs(title = "colorspace Plasma, same curve") +
patchwork::plot_layout(ncol = 1)asColorFun() returns a
circlize::colorRamp2()-compatible function, so the same
specification drives ComplexHeatmap and anything else that
takes a value-to-colour function.
col_fun <- asColorFun(spec, limits = c(-2, 2))
ComplexHeatmap::Heatmap(mat, col = col_fun)
circlize::circos.heatmap(mat, col = col_fun)
image(volcano, col = col_fun(seq(-2, 2, length.out = 64)))Two things to know when borrowing palettes. Several return 8-digit
hex with a fully opaque alpha channel, which brouillet drops, since it
only carries alpha when a colour is actually translucent. And a palette
longer than you need is fine: midpoints only has to be
supplied when you want the stops somewhere other than evenly spaced.
isColor()Vectorised; NA is always FALSE. This
validates every colour argument in the package.
colorWheel()Hues evenly spaced around the wheel, keeping the base colour’s saturation and value.
colorWheel("red", 6)
#> [1] "#FF0000" "#FFFF00" "#00FF00" "#00FFFF" "#0000FF" "#FF00FF"
swatch(colorWheel("red", 12), 'colorWheel("red", 12)')colorComplementary()The opposite hue. An 8-digit alpha is preserved.
colorComplementary("red")
#> [1] "#00FFFF"
colorComplementary("#FF000080")
#> [1] "#00FFFF80"
swatch(c("navy", colorComplementary("navy"), "gold", colorComplementary("gold")),
"pairs: colour and its complement")colorSpread()spread - 1 evenly spaced companions,
excluding the base colour.
colorSpread("blue", 4)
#> [1] "#FF008F" "#FFF000" "#00FF70"
swatch(c("blue", colorSpread("blue", 6)), 'blue, then colorSpread("blue", 6)')colorBlend()One colour part-way from color2 to color1.
Defaults to sRGB; it is the only colour function that drops alpha.
colorBlend("red", "blue", 0.5)
#> [1] "#800080"
colorBlend("black", "white", 0.5)
#> [1] "#808080"
colorBlend("black", "white", 0.5, space = "Lab")
#> [1] "#777777"
swatch(vapply(seq(0, 1, 0.1), function(w) colorBlend("red", "blue", w), character(1)),
"colorBlend(red, blue, weight = 0 .. 1)")colorUpdate()The same idea on a shift/resolution scale,
defaulting to Lab. color2 also accepts NULL
(towards white), "complementary", or a number, which uses
the colorSpread() palette.
colorUpdate("red", "blue", shift = 0)
#> [1] "#0000FF"
colorUpdate("red", shift = 20)
#> [1] "#FFD9CB"
colorUpdate("red", "complementary", shift = 30)
#> [1] "#BBCAB2"
colorUpdate("red", 3, shift = 40)
#> [1] "#8BDF00"
shifts <- function(color2) {
vapply(seq(0, 100, 10), function(s) colorUpdate("red", color2, shift = s),
character(1))
}
swatch(shifts("blue"), 'colorUpdate("red", "blue", shift)') /
swatch(shifts(NULL), 'colorUpdate("red", NULL, shift) -- towards white')Gradients interpolate alpha when any input colour is translucent, and omit it otherwise, so opaque palettes still return 6-digit hex.
resolveGradient()For wrappers: turns whatever a caller supplied – nothing, a template, a specification, or a legacy object – into one validated specification, using your own colour arguments as the fallback.
resolveGradient(NULL, c("white", "pink", "red"), limits = c(0, 1), midpoint = 0.5)$midpoints
#> [1] 0.5
resolveGradient(gradientTemplate(width = 0.2), c("white", "pink", "red"),
limits = c(0, 100), midpoint = 25)$midpoints
#> [1] 0.25
resolveGradient(gradientParams(c("navy", "gold")), c("white", "pink", "red"),
limits = c(0, 1), midpoint = 0.5)$colors
#> [1] "navy" "gold"
resolveGradient(NULL, c("white", "pink", "red"), limits = c(0, 1),
midpoint = NA, quiet = TRUE)$colors
#> [1] "white" "red"quiet = TRUE suppresses the message explaining a dropped
midpoint, for wrappers that report it themselves.
midpoint is in data units and is converted for you. When
it lands on a limit no interior stop can represent it, so the middle
colour is dropped:
hasClipColors()hasClipColors(gradientParams(c("navy", "firebrick")))
#> [1] FALSE
hasClipColors(clipped)
#> [1] TRUEUseful before squishing data: squished values are never out of range, so the clip colours could never appear.
relativeMidpoint()Converts midpoints from data units into the fractions
midpoints expects – the most common mistake when wiring
brouillet into an existing function. Vectorised.
relativeMidpoint(0, c(-2, 2))
#> [1] 0.5
relativeMidpoint(c(-1, 1), c(-2, 2))
#> [1] 0.25 0.75
tryCatch(relativeMidpoint(NA, c(0, 1)), error = function(e) conditionMessage(e))
#> [1] "'value' must be a non-missing numeric vector."
tryCatch(relativeMidpoint(5, c(0, 1)), error = function(e) conditionMessage(e))
#> [1] "Midpoint(s) fall outside 'limits': 5 not within [0, 1]."On a limit it warns and nudges inside by eps, which
signals that the midpoint cannot be an interior stop; drop the middle
colour and use a two-colour ramp instead.
gradient_params()The one snake_case export. It takes the pre-0.2 arguments –
sigma1, sigma2, inflexpoint1,
inflexpoint2, steepness.preset, and
midpoints in data units – and returns an ordinary
specification that works with every function above. New code should use
gradientParams().
old <- gradient_params(colors = c("navy", "white", "firebrick"),
midpoints = 50,
steepness_preset = "medium")
old
#> <brouillet gradient>
#> mode: sigmoid
#> colors: navy -> white -> firebrick
#> space: sRGB (linear)
#> resolution: 100
#> midpoints: 50
#> curve: legacy double sigmoid (pre-0.2 semantics)
head(buildGradient(old, limits = c(0, 100)), 3)
#> value color
#> 1 0 #010181
#> 2 1 #010181
#> 3 2 #020281previewGradient(old, limits = c(0, 100)) +
labs(title = 'gradient_params(steepness_preset = "medium")')Legacy specifications interpolate in sRGB, do not rescale the curve,
read midpoints as data units, and mirror the lower half of
a three-colour gradient – all so existing figures regenerate as they
looked. They also reproduce two original quirks deliberately: a
non-NULL steepness_preset overrides explicit
sigmas, and four-or-more-colour gradients build each segment
backwards.
identical(
buildGradient(gradient_params(c("red", "blue"), sigma1 = 80, sigma2 = 80))$color,
buildGradient(gradient_params(c("red", "blue"), steepness_preset = "low"))$color
)
#> [1] TRUEPass steepness_preset = NULL to make explicit sigmas
take effect.