Package 'brouillet'

Title: Reusable Contrast-Curve Colour Gradients
Description: Build a colour-gradient specification once and reuse it across plots. A contrast curve, parameterised by centre and width in relative units, controls where along the data range the colour change is concentrated, so a narrow band of interest can be expanded and the uninformative remainder compressed. Colours are interpolated in CIE Lab by default. Specifications convert to a value-to-colour function usable by any plotting system, or to 'ggplot2' fill and colour scales, and support two-sided out-of-range (clipping) colours shown as bands on the colourbar.
Authors: Simon Bourdareau [aut, cre]
Maintainer: Simon Bourdareau <[email protected]>
License: MIT + file LICENSE
Version: 0.8.0
Built: 2026-11-24 17:43:46 UTC
Source: https://github.com/SimonBourdareau/brouillet

Help Index


Turn a gradient specification into a colour function

Description

Returns a vectorised function mapping data values to hex colours. This is the interoperability layer: the same specification can then drive 'ComplexHeatmap' ('col ='), base graphics, 'image()', 'gt', raster export, or anything else that accepts a value-to-colour function, not just 'ggplot2' scales.

Usage

asColorFun(params, limits = c(0, 1), na.color = "grey95")

## S3 method for class 'brouillet_color_fun'
print(x, ...)

Arguments

params

A 'brouillet_gradient_params' object from [gradientParams()].

limits

Numeric vector of length 2 giving the data range that maps onto the gradient.

na.color

Colour returned for 'NA', 'NaN' and non-finite input.

x

A 'brouillet_color_fun'.

...

Ignored.

Details

Interface-compatible with 'circlize::colorRamp2()', so it can be passed straight to 'ComplexHeatmap::Heatmap(col = ...)'.

Value

A function of one numeric vector, returning a character vector of hex colours the same length. Values outside 'limits' get the clip colours when the specification defines them, and are otherwise clamped to the end colours.

Examples

p <- gradientParams(colors = c("navy", "white", "firebrick"),
                     midpoints = 0.5, width = 0.3)
col_fun <- asColorFun(p, limits = c(-2, 2))

col_fun(c(-2, -1, 0, 1, 2))
col_fun(c(-99, 99, NA))   # clamped, clamped, na.color


# ComplexHeatmap::Heatmap(mat, col = col_fun)
image(volcano, col = col_fun(seq(90, 200, length.out = 64)))

Use a gradient specification as a ggplot2 colour scale

Description

Use a gradient specification as a ggplot2 colour scale

Usage

asScaleColorGradient(
  params,
  limits = c(0, 1),
  na.value = "grey95",
  guide = guide_colourbar(),
  show.clip = TRUE,
  clip.width = 0.02,
  ...
)

Arguments

params

A 'brouillet_gradient_params' object from [gradientParams()].

limits

Numeric vector of length 2 giving the data range.

na.value

Colour for missing values.

guide

Guide passed to the scale.

show.clip

Show the clip colours as bands beyond 'limits'.

clip.width

Width of each clip band, as a proportion of the range.

...

Passed to [ggplot2::scale_color_gradientn()].

Value

A 'ggplot2' scale object.

Examples

library(ggplot2)

params <- gradientParams(colors = c("navy", "white", "red"), midpoints = 0.5)

ggplot(mtcars, aes(wt, mpg, color = qsec)) +
  geom_point(size = 3) +
  asScaleColorGradient(params, limits = range(mtcars$qsec))

Use a gradient specification as a ggplot2 fill scale

Description

Use a gradient specification as a ggplot2 fill scale

Usage

asScaleFillGradient(
  params,
  limits = c(0, 1),
  na.value = "grey95",
  guide = guide_colourbar(),
  show.clip = TRUE,
  clip.width = 0.02,
  ...
)

Arguments

params

A 'brouillet_gradient_params' object from [gradientParams()].

limits

Numeric vector of length 2 giving the data range.

na.value

Colour for missing values.

guide

Guide passed to the scale.

show.clip

Show the clip colours as bands beyond 'limits'.

clip.width

Width of each clip band, as a proportion of the range.

...

Passed to [ggplot2::scale_fill_gradientn()].

Details

When 'show.clip = TRUE' and clip colours are set, the scale limits are widened by 'clip.width' on each side so the clipped bands are visible in the colourbar.

Value

A 'ggplot2' scale object.

Examples

library(ggplot2)

params <- gradientParams(colors = c("navy", "white", "red"), midpoints = 0.5)

df <- expand.grid(x = 1:10, y = 1:10)
df$z <- runif(100)

ggplot(df, aes(x, y, fill = z)) +
  geom_tile() +
  asScaleFillGradient(params)

Add blended out-of-range colours to a gradient

Description

Like [clippingGradient()], but the clip colours fade into the ends of the gradient over a short ramp instead of switching abruptly.

Usage

blendingClippingGradient(
  gradient,
  low.value = min(gradient$value),
  high.value = max(gradient$value),
  low.clip.color,
  high.clip.color,
  resolution = 100,
  .legacy = FALSE
)

Arguments

gradient

A gradient data frame with 'value' and 'color' columns, or a specification from [gradientParams()] or [gradientTemplate()].

low.value, high.value

Window to keep. Defaults to the gradient's own range.

low.clip.color, high.clip.color

Colours for values below and above the window.

resolution

Gradient resolution used to size the blend region; the blend uses 'max(5, 10% of resolution)' steps on each side.

.legacy

Reproduce the pre-0.2 blend, which stopped short of the high clip colour. Set automatically for specifications from [gradient_params()]; not intended to be passed directly.

Value

A gradient data frame with extra rows at both ends.

Examples

grad <- sigmoidGradient2("red", "blue")
blendingClippingGradient(grad, 0, 1, "grey80", "black")[1:3, ]

Build a gradient data frame from a specification

Description

Materialises a [gradientParams()] specification over a data range, as a table of value/colour stops. Use [asColorFun()] instead when you want to colour arbitrary values.

Usage

buildGradient(params, limits = c(0, 1))

Arguments

params

A 'brouillet_gradient_params' object.

limits

Numeric vector of length 2 giving the data range.

Value

A data frame with 'value' and 'color' columns.

Examples

p <- gradientParams(colors = c("navy", "white", "firebrick"), midpoints = 0.5)
head(buildGradient(p, limits = c(-2, 2)))

Add hard out-of-range colours to a gradient

Description

Restricts a gradient to '[low.value, high.value]' and appends a single stop just below and just above that window, so values outside the window render in dedicated "clipped" colours.

Usage

clippingGradient(
  gradient,
  low.value = min(gradient$value),
  high.value = max(gradient$value),
  low.clip.color,
  high.clip.color
)

Arguments

gradient

A gradient data frame with 'value' and 'color' columns, or a specification from [gradientParams()] or [gradientTemplate()].

low.value, high.value

Window to keep. Defaults to the gradient's own range.

low.clip.color, high.clip.color

Colours for values below and above the window.

Value

A gradient data frame with two extra rows.

Examples

grad <- sigmoidGradient2("red", "blue")
clipped <- clippingGradient(grad, 0.2, 0.8, "grey80", "black")
head(clipped, 3)

Blend two colours

Description

Interpolation between two colours. Alpha channels are ignored.

Usage

colorBlend(color1, color2, weight = 0.5, space = "sRGB")

Arguments

color1

First colour.

color2

Second colour.

weight

Weight given to 'color1', between 0 and 1.

space

Interpolation space. Defaults to '"sRGB"' for this low-level helper, unlike the gradient builders, which default to '"Lab"'.

Value

A single hexadecimal colour string.

Examples

colorBlend("red", "blue", 0.5)
colorBlend("black", "white", 0.5, space = "Lab")

Find the complementary colour

Description

Returns the colour on the opposite side of the HSV hue wheel.

Usage

colorComplementary(color)

Arguments

color

Input colour.

Value

A single hexadecimal colour string.

Examples

colorComplementary("red")

Generate evenly spread colours around the wheel

Description

Divides the hue wheel into 'spread' sections and returns the 'spread - 1' colours that are not the base colour.

Usage

colorSpread(color, spread = 3, resolution = 100)

Arguments

color

Base colour.

spread

Number of divisions of the wheel (>= 2).

resolution

Resolution of the underlying colour wheel; coerced up to 'spread * 10' when smaller than 'spread'.

Value

Character vector of 'spread - 1' hexadecimal colours.

Examples

colorSpread("blue", 4) # 3 colours, blue excluded

Shift a colour towards a second colour

Description

Interpolates along a colour ramp between 'color' and a second colour, returning the entry at the requested position.

Usage

colorUpdate(color, color2 = NULL, shift = 50, resolution = 100, space = "Lab")

Arguments

color

Primary colour.

color2

Secondary colour. One of: a valid colour; the string '"complementary"' (uses [colorComplementary()]); a single number '>= 2' (uses the [colorSpread()] palette of 'color'); or 'NULL' for white.

shift

Position along the ramp, on the same scale as 'resolution' (0 = fully 'color2', 'resolution' = fully 'color').

resolution

Number of steps in the ramp (>= 2).

space

Colour interpolation space, '"Lab"' (default) or '"sRGB"'.

Value

A single hexadecimal colour string.

Examples

colorUpdate("red", "blue", shift = 50)
colorUpdate("red", "complementary", shift = 30)
colorUpdate("red", shift = 20) # towards white

Generate a colour wheel

Description

Creates 'num' colours evenly spaced in hue around the HSV wheel, starting at 'color' and preserving its saturation and value.

Usage

colorWheel(color, num)

Arguments

color

Base colour.

num

Number of colours to generate (positive integer).

Value

Character vector of hexadecimal colours.

Examples

colorWheel("red", 12)

Monotone contrast curve

Description

An S-shaped mapping of \[0, 1\] onto \[0, 1\], used to control where a gradient's colour change is concentrated. Compressing the uninformative part of a data range and expanding a band of interest is the colour-scale equivalent of adjusting a contrast (gamma) slider.

Usage

contrastCurve(x, center = 0.5, width = 0.4, asymmetry = 0, rescale = TRUE)

Arguments

x

Numeric vector of relative positions in \[0, 1\].

center

Position of the 50% point, in \[0, 1\]. This is where the colour change is fastest.

width

Width of the transition: the span of 'x' over which the curve goes from 5% to 95%. Small values give a sharp, threshold-like scale; 'width = 1' is close to linear. Values above 1 flatten the curve further.

asymmetry

Between -1 and 1. Shifts softness from the low side to the high side: positive values make the curve sharp below 'center' and gradual above it (a long upper tail), negative values do the reverse. '0' is symmetric.

rescale

When 'TRUE' (default), the curve is linearly rescaled so that 'x = 0' maps to exactly 0 and 'x = 1' to exactly 1, guaranteeing that the end colours of a gradient are actually reached.

Details

Below 'center' the curve is a logistic of scale 'width * (1 - asymmetry)', above it a logistic of scale 'width * (1 + asymmetry)'; the two halves meet at 0.5, so 'center' is always the 50% point and the 5-95% span is always approximately 'width'.

Value

Numeric vector the same length as 'x', non-decreasing, in \[0, 1\].

Examples

x <- seq(0, 1, length.out = 11)
round(contrastCurve(x), 3)                    # default, symmetric
round(contrastCurve(x, width = 0.1), 3)       # near-threshold
round(contrastCurve(x, asymmetry = 0.8), 3)   # long upper tail


plot(seq(0, 1, 0.005), contrastCurve(seq(0, 1, 0.005), width = 0.25),
     type = "l", xlab = "data position", ylab = "colour position")

Gradient from a custom mapping function

Description

Maps relative position through a user-supplied monotonic function, then samples a single ramp built from all of 'colors'.

Usage

customGradientFun(
  colors,
  mapping.fun,
  resolution = 100,
  low.value = 0,
  high.value = 1,
  space = "Lab",
  interpolate = "linear"
)

Arguments

colors

Vector of at least two colours.

mapping.fun

A vectorised, non-decreasing function mapping \[0, 1\] to \[0, 1\].

resolution

Number of gradient steps (>= 2). The returned data frame has 'resolution + 1' rows.

low.value, high.value

Data-unit bounds of the gradient.

space

Colour interpolation space: '"Lab"' (default, perceptual) or '"sRGB"' (the pre-0.2.0 behaviour).

interpolate

'"linear"' or '"spline"' interpolation between stops.

Value

A data frame with columns 'value' and 'color'.

Examples

# Slow start, fast finish
customGradientFun(c("navy", "firebrick"), function(x) x^2)[1:3, ]

Double sigmoid curve

Description

Builds a weighting function from the product of two logistic curves: the mapping used by brouillet before 0.2, and a four-parameter family that [contrastCurve()] cannot express. A curve with distant inflexion points and small widths gives a staircase rather than a single transition.

Usage

doubleSigmoid(sigma1, sigma2, inflexpoint1 = 0.3, inflexpoint2 = 0.4)

Arguments

sigma1, sigma2

Widths of the two logistic factors, on an internal 0-1000 grid. Smaller is sharper.

inflexpoint1, inflexpoint2

Centres of the two factors, as fractions in \[0, 1\], with 'inflexpoint1 < inflexpoint2'.

Details

Unlike [contrastCurve()] this is not rescaled, so it does not reach 0 and 1 at the ends of the range. That is the behaviour the pre-0.2 gradients had.

Value

A function mapping \[0, 1\] to \[0, 1\], suitable for the 'curve.fun' argument of [gradientParams()].

Examples

f <- doubleSigmoid(200, 200, 0.3, 0.4)
round(f(c(0, 0.25, 0.5, 0.75, 1)), 3)

gradientParams(c("navy", "firebrick"),
               curve.fun = doubleSigmoid(50, 50, 0.2, 0.8))

Create a gradient specification using the pre-0.2 arguments

Description

A drop-in replacement for the original 'gradient_params()': same arguments, same meanings, same rendered output. It returns a modern 'brouillet_gradient_params' object, so the result works with every current function. New code should use [gradientParams()].

Usage

gradient_params(
  colors = NULL,
  midpoints = NULL,
  sigma1 = NULL,
  sigma2 = NULL,
  inflexpoint1 = 0.3,
  inflexpoint2 = 0.4,
  resolution = 100,
  steepness_preset = "low",
  low.clip.color = NULL,
  high.clip.color = NULL,
  blend.clip = FALSE,
  gradient_mode = "sigmoid",
  mapping_fun = NULL
)

Arguments

colors

Vector of colours, or 'NULL' for a template.

midpoints

Interior stop positions **in data units**, as before. Resolved against 'limits' when the gradient is built.

sigma1, sigma2

Widths of the two logistic factors.

inflexpoint1, inflexpoint2

Transition points in \[0, 1\].

resolution

Number of gradient steps.

steepness_preset

One of [steepnessPresets()]; used when 'sigma1' and 'sigma2' are 'NULL'.

low.clip.color, high.clip.color

Colours for out-of-range values.

blend.clip

Fade the clip colours in rather than switching.

gradient_mode

'"sigmoid"', '"linear"' or '"custom"'.

mapping_fun

Function for 'gradient_mode = "custom"'.

Details

Legacy specifications differ from [gradientParams()] defaults in four ways, all chosen so old figures regenerate unchanged: colours are interpolated in sRGB, the curve is not rescaled so the end colours are approached but not reached, 'midpoints' are data-unit positions rather than fractions, and a three-colour gradient mirrors its lower half.

Value

A 'brouillet_gradient_params' object carrying legacy semantics.

Examples

p <- gradient_params(colors = c("navy", "white", "firebrick"),
                     midpoints = 0.5, steepness_preset = "medium")
p

head(buildGradient(p, limits = c(0, 1)), 3)

Create a gradient specification

Description

Bundles every setting needed to build a gradient into a portable object, so one specification can drive several plots. Convert it with [asColorFun()] (any plotting system), [asScaleFillGradient()] or [asScaleColorGradient()] ('ggplot2'), or materialise it with [buildGradient()].

Usage

gradientParams(
  colors = NULL,
  midpoints = NULL,
  center = 0.5,
  width = NULL,
  asymmetry = 0,
  resolution = 100,
  space = "Lab",
  interpolate = "linear",
  rescale = NULL,
  low.clip.color = NULL,
  high.clip.color = NULL,
  blend.clip = FALSE,
  gradient.mode = "sigmoid",
  mapping.fun = NULL,
  curve.fun = NULL,
  steepness.preset = NULL
)

## S3 method for class 'brouillet_gradient_params'
print(x, ...)

Arguments

colors

Vector of at least two colours. Colour 'i' runs to colour 'i + 1' as the data value increases. May be 'NULL', which creates an incomplete specification: curve, clipping and interpolation settings are recorded, and the palette is supplied later with [updateGradient()]. Such an object cannot be built or plotted until it has colours.

midpoints

Relative positions of the interior colour stops, strictly inside (0, 1) and strictly increasing, of length 'length(colors) - 2'. Defaults to evenly spaced stops.

center, width, asymmetry

Curve shape; see [contrastCurve()]. 'width' defaults to 0.4 for 'gradient.mode = "sigmoid"' and 1 for '"linear"'.

resolution

Number of gradient steps (>= 2) used when sampling stops.

space

Colour interpolation space: '"Lab"' (default, perceptual) or '"sRGB"'.

interpolate

'"linear"' or '"spline"'.

rescale

Force the end colours to be reached exactly; see [contrastCurve()]. Defaults to 'TRUE' for '"sigmoid"' and '"custom"', 'FALSE' for '"linear"'.

low.clip.color, high.clip.color

Colours for out-of-range values. 'NULL' (default) disables clipping.

blend.clip

Fade the clip colours into the gradient ends instead of switching abruptly.

gradient.mode

'"sigmoid"', '"linear"' or '"custom"'.

mapping.fun

Monotonic function mapping \[0, 1\] to \[0, 1\], required when 'gradient.mode = "custom"'.

curve.fun

Function mapping \[0, 1\] to \[0, 1\] applied *within each segment*, replacing the built-in curve. Use it for shapes 'center' / 'width' / 'asymmetry' cannot express, such as [doubleSigmoid()]. Unlike 'mapping.fun' it does not change how colours are segmented.

steepness.preset

One of [steepnessPresets()]: a named shorthand for 'center', 'width' and 'asymmetry', carried over from the pre-0.2 API. Any of those three given explicitly overrides the preset. The preset reproduces the old curve's shape in the modern family, not the old rendering; use [gradient_params()] for that.

x

A 'brouillet_gradient_params' object.

...

Ignored.

Value

An object of class 'brouillet_gradient_params'.

Examples

# Diverging, transition concentrated near the centre
p <- gradientParams(colors = c("navy", "white", "firebrick"),
                     midpoints = 0.5, width = 0.3)
p

# Threshold-like scale with out-of-range colours
gradientParams(colors = c("grey90", "firebrick"),
                center = 0.8, width = 0.1,
                low.clip.color = "white", high.clip.color = "black")

Create a gradient template (curve settings without colours)

Description

Captures everything [gradientParams()] takes except the colours, for use with functions that supply their own palette. Combine with [withColors()] to get a usable specification.

Usage

gradientTemplate(
  center = 0.5,
  width = NULL,
  asymmetry = 0,
  resolution = 100,
  space = "Lab",
  interpolate = "linear",
  rescale = NULL,
  low.clip.color = NULL,
  high.clip.color = NULL,
  blend.clip = FALSE,
  gradient.mode = "sigmoid",
  mapping.fun = NULL,
  curve.fun = NULL,
  steepness.preset = NULL
)

## S3 method for class 'brouillet_gradient_template'
print(x, ...)

Arguments

center, width, asymmetry

Curve shape; see [contrastCurve()]. 'width' defaults to 0.4 for 'gradient.mode = "sigmoid"' and 1 for '"linear"'.

resolution

Number of gradient steps (>= 2) used when sampling stops.

space

Colour interpolation space: '"Lab"' (default, perceptual) or '"sRGB"'.

interpolate

'"linear"' or '"spline"'.

rescale

Force the end colours to be reached exactly; see [contrastCurve()]. Defaults to 'TRUE' for '"sigmoid"' and '"custom"', 'FALSE' for '"linear"'.

low.clip.color, high.clip.color

Colours for out-of-range values. 'NULL' (default) disables clipping.

blend.clip

Fade the clip colours into the gradient ends instead of switching abruptly.

gradient.mode

'"sigmoid"', '"linear"' or '"custom"'.

mapping.fun

Monotonic function mapping \[0, 1\] to \[0, 1\], required when 'gradient.mode = "custom"'.

curve.fun

Function mapping \[0, 1\] to \[0, 1\] applied *within each segment*, replacing the built-in curve. Use it for shapes 'center' / 'width' / 'asymmetry' cannot express, such as [doubleSigmoid()]. Unlike 'mapping.fun' it does not change how colours are segmented.

steepness.preset

One of [steepnessPresets()]: a named shorthand for 'center', 'width' and 'asymmetry', carried over from the pre-0.2 API. Any of those three given explicitly overrides the preset. The preset reproduces the old curve's shape in the modern family, not the old rendering; use [gradient_params()] for that.

x

A 'brouillet_gradient_template'.

...

Ignored.

Details

All arguments are validated immediately against a placeholder palette, so a bad curve or mode fails here rather than at plot time.

Value

An object of class 'brouillet_gradient_template'.

Examples

tpl <- gradientTemplate(center = 0.4, width = 0.25)
tpl

# A host function fills in its own colours
p <- withColors(tpl, c("blue", "white", "red"), midpoints = 0.5)
head(buildGradient(p))

Does a specification define out-of-range colours?

Description

Does a specification define out-of-range colours?

Usage

hasClipColors(params)

Arguments

params

A 'brouillet_gradient_params' object.

Details

Mainly useful in wrappers that squish data before plotting: squished values are never out of range, so the clip colours can never appear.

Value

'TRUE' when either clip colour is set.

Examples

hasClipColors(gradientParams(c("navy", "firebrick")))
hasClipColors(gradientParams(c("navy", "firebrick"), high.clip.color = "gold"))

Check whether a string is a valid colour

Description

Tests whether each element can be converted to RGB by [grDevices::col2rgb()]. Vectorised; 'NA' is never a valid colour.

Usage

isColor(color)

Arguments

color

Character (or numeric palette index) vector of candidate colours.

Value

Logical vector the same length as 'color'.

Examples

isColor("red")
isColor(c("#FF0000", "notacolor"))

Two-colour linear gradient

Description

Piecewise-linear ramp: constant 'color1', a straight-line blend of total span 'width' centred on 'center', then constant 'color2'. The default ('center = 0.5', 'width = 1') is an ordinary linear gradient.

Usage

linearGradient2(
  color1,
  color2,
  center = 0.5,
  width = 1,
  asymmetry = 0,
  resolution = 100,
  low.value = 0,
  high.value = 1,
  space = "Lab",
  interpolate = "linear",
  rescale = FALSE
)

Arguments

color1

Colour at the low end.

color2

Colour at the high end.

center

Position of the 50% point, in \[0, 1\].

width

Span of the ramp, in relative units. Values below 1 leave flat regions at both ends.

asymmetry

Between -1 and 1; makes the ramp steeper on one side of 'center' than the other.

resolution

Number of gradient steps (>= 2). The returned data frame has 'resolution + 1' rows.

low.value, high.value

Data-unit bounds of the gradient.

space

Colour interpolation space: '"Lab"' (default, perceptual) or '"sRGB"' (the pre-0.2.0 behaviour).

interpolate

'"linear"' or '"spline"' interpolation between stops.

rescale

Force the end colours to be reached exactly; see [contrastCurve()].

Value

A data frame with columns 'value' and 'color'.

Examples

linearGradient2("navy", "firebrick")[1:3, ]

# Flat below 0.25 and above 0.75
linearGradient2("navy", "firebrick", width = 0.5)[1:3, ]

Multi-colour linear gradient

Description

Chains linear ramps between colour stops.

Usage

linearGradientn(
  colors,
  midpoints = NULL,
  center = 0.5,
  width = 1,
  asymmetry = 0,
  resolution = 100,
  low.value = 0,
  high.value = 1,
  space = "Lab",
  interpolate = "linear",
  rescale = FALSE
)

Arguments

colors

Vector of at least two colours. Segment 'i' runs from 'colors[i]' to 'colors[i + 1]' as 'value' increases.

midpoints

Relative positions of the interior stops, strictly inside (0, 1), strictly increasing, of length 'length(colors) - 2'. Defaults to evenly spaced stops.

center

Position of the 50% point, in \[0, 1\].

width

Span of the ramp, in relative units. Values below 1 leave flat regions at both ends.

asymmetry

Between -1 and 1; makes the ramp steeper on one side of 'center' than the other.

resolution

Number of gradient steps (>= 2). The returned data frame has 'resolution + 1' rows.

low.value, high.value

Data-unit bounds of the gradient.

space

Colour interpolation space: '"Lab"' (default, perceptual) or '"sRGB"' (the pre-0.2.0 behaviour).

interpolate

'"linear"' or '"spline"' interpolation between stops.

rescale

Force the end colours to be reached exactly; see [contrastCurve()].

Value

A data frame with columns 'value' and 'color'.

Examples

linearGradientn(c("navy", "white", "firebrick"), 0.5)[1:3, ]

Preview a gradient

Description

Renders a gradient specification as a single horizontal band.

Usage

previewGradient(params, limits = c(0, 1), n.ticks = 5, clip.pad = 0.08)

Arguments

params

A 'brouillet_gradient_params' object.

limits

Numeric vector of length 2 giving the range to preview.

n.ticks

Number of x-axis ticks (>= 2).

clip.pad

When the specification sets clip colours, how far beyond 'limits' to draw, as a proportion of the range, so the clipped regions are visible. Ignored when there is no clipping.

Value

A 'ggplot' object.

Examples

params <- gradientParams(colors = c("blue", "white", "red"), midpoints = 0.5)
previewGradient(params)

Convert a data-unit midpoint to a relative one

Description

brouillet expresses 'midpoints', 'center' and 'width' as fractions of the gradient range, while host functions usually hold a midpoint in data units (a Jaccard value of 1/3, an NMI value of 0). This converts the latter to the former, which is the single most common mistake when wiring brouillet into an existing plotting function.

Usage

relativeMidpoint(value, limits, eps = 1e-06)

Arguments

value

Numeric midpoint(s) in data units, increasing.

limits

Length-2 numeric giving the data range.

eps

Values landing exactly on a limit are nudged inside by this much, since a stop at 0 or 1 is degenerate.

Value

Numeric vector of relative positions, strictly inside (0, 1).

Examples

relativeMidpoint(1 / 3, limits = c(0.2, 0.8))   # 0.2222
relativeMidpoint(0, limits = c(-0.1, 0.1))      # 0.5

Resolve whatever a caller supplied into a specification

Description

Turns the gradient argument of a plotting function into a validated specification, whichever form the caller used: nothing, a template, or a finished specification. Written for wrappers that expose their own colour arguments and a midpoint in data units.

Usage

resolveGradient(
  spec = NULL,
  colors,
  limits = NULL,
  midpoint = NULL,
  gradient.mode = "linear",
  quiet = FALSE
)

Arguments

spec

'NULL', a 'brouillet_gradient_template', or a 'brouillet_gradient_params' object (including one from [gradient_params()]).

colors

Fallback palette, used when 'spec' is 'NULL' or carries no colours. Two or three colours; a 'NULL' middle colour collapses the vector, so 'c(low, mid, high)' handles both cases.

limits

Numeric vector of length 2: the data range the gradient will be drawn over. Required when 'midpoint' is given.

midpoint

Position of the middle colour **in data units**, or 'NULL'. Ignored unless 'colors' has three entries.

gradient.mode

Mode for the specification built when 'spec' is 'NULL'.

quiet

Suppress the message explaining why a midpoint was dropped.

Details

Three things make this fiddly enough to be worth a function:

* ‘midpoints' are fractions of the range, while a plotting function’s 'midpoint' argument is usually in data units. The conversion needs 'limits', which is why they are an argument here. * A midpoint can land on or outside a limit, which no interior stop can represent. The middle colour is dropped and a message explains why. * Specifications from [gradient_params()] read 'midpoints' as data units, so they need the opposite treatment. That is handled here.

When 'spec' already carries colours they win; only its interior stop is updated, and only for a three-colour palette. Set one clip colour and the other is filled from the matching end of the ramp, so the colourbar does not gain a band on one side only.

Value

A 'brouillet_gradient_params' object ready for [asColorFun()], [asScaleFillGradient()] or [buildGradient()].

Examples

resolveGradient(NULL, c("white", "pink", "red"), limits = c(0, 1), midpoint = 0.5)

resolveGradient(gradientTemplate(width = 0.2), c("white", "pink", "red"),
                limits = c(0, 100), midpoint = 50)

# A midpoint on a limit cannot be an interior stop
resolveGradient(NULL, c("white", "pink", "red"), limits = c(0, 1), midpoint = 0)

# A caller's own specification is respected
resolveGradient(gradientParams(c("navy", "gold")), c("white", "pink", "red"),
                limits = c(0, 1), midpoint = 0.5)$colors

Reverse a gradient specification

Description

Mirrors a specification: colour order, midpoints, curve centre, curve asymmetry and clip colours are all flipped, so the reversed gradient is the mirror image of the original rather than just its colours in reverse.

Usage

reverseGradient(params)

Arguments

params

A 'brouillet_gradient_params' object.

Value

A new 'brouillet_gradient_params' object.

Examples

p <- gradientParams(colors = c("navy", "white", "firebrick"),
                     midpoints = 0.4, center = 0.3, asymmetry = 0.5)
reverseGradient(p)

Two-colour contrast gradient

Description

Builds a gradient between two colours where the colour change is concentrated around 'center', following [contrastCurve()].

Usage

sigmoidGradient2(
  color1,
  color2,
  center = 0.5,
  width = 0.4,
  asymmetry = 0,
  resolution = 100,
  low.value = 0,
  high.value = 1,
  space = "Lab",
  interpolate = "linear",
  rescale = TRUE
)

Arguments

color1

Colour at the low end.

color2

Colour at the high end.

center, width, asymmetry

Curve shape; see [contrastCurve()].

resolution

Number of gradient steps (>= 2). The returned data frame has 'resolution + 1' rows.

low.value, high.value

Data-unit bounds of the gradient.

space

Colour interpolation space: '"Lab"' (default, perceptual) or '"sRGB"' (the pre-0.2.0 behaviour).

interpolate

'"linear"' or '"spline"' interpolation between stops.

rescale

Force the end colours to be reached exactly; see [contrastCurve()].

Value

A data frame with columns 'value' and 'color', carrying 'gradientParams' and 'gradient_type' attributes.

Examples

g <- sigmoidGradient2("navy", "firebrick")
head(g)

# Sharpen the transition and move it up the range
sigmoidGradient2("navy", "firebrick", center = 0.7, width = 0.15)[1:3, ]

Three-colour contrast gradient

Description

Two contrast ramps meeting at a central colour, the usual shape for diverging scales.

Usage

sigmoidGradient3(
  color1,
  color2,
  midpoint.color,
  center = 0.5,
  width = 0.4,
  asymmetry = 0,
  resolution = 100,
  low.value = 0,
  midpoint.value = 0.5,
  high.value = 1,
  space = "Lab",
  interpolate = "linear",
  rescale = TRUE
)

Arguments

color1

Colour at the low end.

color2

Colour at the high end.

midpoint.color

Colour at the centre of the gradient.

center, width, asymmetry

Curve shape; see [contrastCurve()].

resolution

Number of gradient steps (>= 2). The returned data frame has 'resolution + 1' rows.

low.value, high.value

Data-unit bounds of the gradient.

midpoint.value

Data-unit position of the central colour; must lie strictly between 'low.value' and 'high.value'.

space

Colour interpolation space: '"Lab"' (default, perceptual) or '"sRGB"' (the pre-0.2.0 behaviour).

interpolate

'"linear"' or '"spline"' interpolation between stops.

rescale

Force the end colours to be reached exactly; see [contrastCurve()].

Details

The curve is applied within each half, so with the default 'center = 0.5' and 'asymmetry = 0' the result is symmetric about 'midpoint.value'.

Value

A data frame with columns 'value' and 'color'.

Examples

g <- sigmoidGradient3("navy", "firebrick", "white", width = 0.3)
head(g)

Multi-colour contrast gradient

Description

Chains contrast ramps between three or more colour stops.

Usage

sigmoidGradientn(
  colors,
  midpoints = NULL,
  center = 0.5,
  width = 0.4,
  asymmetry = 0,
  resolution = 100,
  low.value = 0,
  high.value = 1,
  space = "Lab",
  interpolate = "linear",
  rescale = TRUE
)

Arguments

colors

Vector of at least three colours. Segment 'i' runs from 'colors[i]' to 'colors[i + 1]' as 'value' increases.

midpoints

Relative positions of the interior stops, strictly inside (0, 1), strictly increasing, of length 'length(colors) - 2'. Defaults to evenly spaced stops.

center, width, asymmetry

Curve shape; see [contrastCurve()].

resolution

Number of gradient steps (>= 2). The returned data frame has 'resolution + 1' rows.

low.value, high.value

Data-unit bounds of the gradient.

space

Colour interpolation space: '"Lab"' (default, perceptual) or '"sRGB"' (the pre-0.2.0 behaviour).

interpolate

'"linear"' or '"spline"' interpolation between stops.

rescale

Force the end colours to be reached exactly; see [contrastCurve()].

Value

A data frame with columns 'value' and 'color'.

Examples

g <- sigmoidGradientn(c("navy", "white", "firebrick", "black"), c(0.4, 0.8))
head(g)

Steepness presets

Description

Named curve shapes carried over from the pre-0.2 API. Each row gives the original 'sigma1'/'sigma2' pair, used by [gradient_params()] and [doubleSigmoid()], together with the 'center'/'width'/'asymmetry' that reproduce it in the modern curve, used by 'gradientParams(steepness.preset =)'.

Usage

steepnessPresets()

Details

The modern columns were fitted to the 5%, 50% and 95% points of the rescaled legacy curve, so a preset gives the same overall shape rather than identical colours. Use [gradient_params()] when you need the old rendering exactly.

Value

A data frame with one row per preset.

Examples

steepnessPresets()

gradientParams(c("navy", "firebrick"), steepness.preset = "high")

Modify a gradient specification

Description

Returns a new specification with the named fields replaced, revalidated as if it had been built by [gradientParams()] from scratch. This is the supported way to complete a colourless template, or to adjust one setting without restating the rest.

Usage

updateGradient(params, ...)

Arguments

params

A 'brouillet_gradient_params' object.

...

Named fields to replace; any argument of [gradientParams()]. Pass 'NULL' to reset a field to its default.

Details

When 'colors' changes length and 'midpoints' is not supplied, stale midpoints are dropped (with a warning) and the evenly spaced default is used, rather than failing on a length mismatch.

Value

A new 'brouillet_gradient_params' object.

Examples

# A reusable template: curve and clipping now, colours later
tmpl <- gradientParams(colors = NULL, width = 0.3, high.clip.color = "black")
tmpl

p <- updateGradient(tmpl, colors = c("navy", "white", "firebrick"))
p

# Adjust one field
updateGradient(p, width = 0.1)$width

Attach colours to a template or replace those of a specification

Description

The bridge between a caller-supplied curve and a host-supplied palette. Also useful for swapping the palette of an existing specification while keeping its curve, clipping and interpolation settings.

Usage

withColors(x, colors, midpoints = NULL)

Arguments

x

A 'brouillet_gradient_template' or 'brouillet_gradient_params'.

colors

Vector of at least two colours.

midpoints

Relative positions of the interior stops, in (0, 1). 'NULL' uses evenly spaced stops. Data-unit positions must be converted first with [relativeMidpoint()].

Value

A 'brouillet_gradient_params' object.

Examples

tpl <- gradientTemplate(width = 0.3)
withColors(tpl, c("blue", "white", "red"), midpoints = 0.5)

# Same curve, different palette
p <- gradientParams(c("navy", "white", "firebrick"), width = 0.2)
withColors(p, c("black", "grey", "gold"))