Skip to content

@graphty/graphty-element / schema / interpolatePalette

Function: interpolatePalette() ​

interpolatePalette(value, colors, missingColor?): string

Defined in: graphty-element/src/utils/styleHelpers/color/interpolation.ts:151

Interpolate a value within a color palette.

A value of 0 gives the first colour, 1 gives the last, and a value between them is mixed from the two nearest anchors. A finite value outside 0-1 is clamped to the nearest end, which is long-standing behaviour that callers such as the diverging ramps rely on after they re-centre a value around a midpoint.

A value that cannot be placed on the ramp at all -- undefined, null, NaN or an infinity -- returns missingColor. That is the whole point of the function: it is called from a repaint loop with no try/catch, so it must answer for a node the algorithm never measured rather than abort the frame and leave every later node unstyled.

A palette anchor that is not a hex colour also returns missingColor, because it is only discovered when a value happens to sample that anchor: throwing there would take down the repaint for some nodes and not others, which is exactly the failure this function exists to prevent. An entire ramp band drawn in the missing colour is loud enough to find the typo.

An EMPTY palette does throw. It is a programmer error in the palette definition, not a bad value: there is no colour in it to return for anybody, it is detected before a single element is painted, and it therefore fails identically on the first call rather than part way through a frame. Returning the missing colour instead would paint an entire graph magenta and call it data.

Parameters ​

value ​

number | null | undefined

Value to map (0-1); outside that range it clamps, and a value that is not a finite number yields missingColor.

colors ​

readonly string[]

Array of hex color strings; must not be empty.

missingColor? ​

string = MISSING_DATA_COLOR

The colour to return for a value that cannot be placed on the ramp. Defaults to MISSING_DATA_COLOR.

Returns ​

string

Interpolated color (hex string).

Throws ​

If colors is empty.

Example ​

ts
interpolatePalette(0.5, VIRIDIS_COLORS)        // "#23908c"
interpolatePalette(undefined, VIRIDIS_COLORS)  // "#ff00ff", the missing colour