Expressions

To enable custom calculations, Vega includes its own expression language for writing basic formulas. For example, these expressions are used by the filter and formula transforms to modify data, and within signal definitions to calculate updated values in response to user input.

The expression language is a restricted subset of JavaScript. All basic arithmetic, logical and property access expressions are supported, as are boolean, number, string, object ({}) and array ([]) literals. Ternary operators (ifTest ? thenValue : elseValue) and a special if(test, thenValue, elseValue) function are supported.

To keep the expression language simple, secure and free of unwanted side effects, the following elements are not allowed: assignment operators (=, += etc), pre/postfix updates (++), new expressions, and most control flow statements (for, while, switch, etc). In addition, function calls involving nested properties (foo.bar()) are not allowed. Instead, the expression language supports a collection of functions defined in the top-level scope.

This page documents the expression language. If you are interested in implementation aspects, the bulk of the expression language – including parsing, code generation, and some of the constant and function definitions – are maintained in the vega-expression module.

Expression Language Reference

Bound Variables

The expression language includes a number of automatically-bound named variables.

# datum

The current input data object, available within data transform and event handler expressions. To lookup object properties, use normal JavaScript syntax: datum.value or datum['My Value'].

# event

If the expression is being invoked in response to an event, an event variable is defined. This variable consists of a standard JavaScript DOM event, providing access to bound properties of the event, such as event.metaKey or event.keyCode.

# signal names

Any in-scope signal value can be referenced directly by name. For example, if you have defined a signal named hover within your Vega specification, you can refer to it directly within an expression (e.g., hover.value).

Back to Top

Constants

Constant values that can be referenced by name within expressions.

# NaN
Not a number. Same as the JavaScript literal NaN.

# E
The transcendental number e. Same as JavaScript’s Math.E.

# LN2
The natural log of 2. Same as JavaScript’s Math.LN2.

# LN10
The natural log of 10. Same as JavaScript’s Math.LN10.

# LOG2E
The base 2 logarithm of e. Same as JavaScript’s Math.LOG2E.

# LOG10E
The base 10 logarithm e. Same as JavaScript’s Math.LOG10E.

# MAX_VALUE
The largest positive numeric value. Same as JavaScript’s Number.MAX_VALUE.

# MIN_VALUE
The smallest positive numeric value. Same as JavaScript’s Number.MIN_VALUE.

# PI
The transcendental number π. Same as JavaScript’s Math.PI.

# SQRT1_2
The square root of 0.5. Same as JavaScript’s Math.SQRT1_2.

# SQRT2
The square root of 2. Same as JavaScript’s Math.SQRT2.

Back to Top

Type Checking Functions

Predicate functions for checking value types.

# isArray(value)
Returns true if value is an array, false otherwise.

# isBoolean(value)
Returns true if value is a boolean (true or false), false otherwise.

# isDate(value)
Returns true if value is a Date object, false otherwise. This method will return false for timestamp numbers or date-formatted strings; it recognizes Date objects only.

# isNumber(value)
Returns true if value is a number, false otherwise. NaN and Infinity are considered numbers.

# isObject(value)
Returns true if value is an object, false otherwise. Following JavaScript typeof convention, null values are considered objects.

# isRegExp(value)
Returns true if value is a RegExp (regular expression) object, false otherwise.

# isString(value)
Returns true if value is a string, false otherwise.

Type Coercion Functions

Functions for coercing values to a desired type.

# toBoolean(value)
Coerces the input value to a string. Null values and empty strings are mapped to null.

# toDate(value)
Coerces the input value to a Date instance. Null values and empty strings are mapped to null. If an optional parser function is provided, it is used to perform date parsing, otherwise Date.parse is used. Be aware that Date.parse has different implementations across browsers!

# toNumber(value)
Coerces the input value to a number. Null values and empty strings are mapped to null.

# toString(value)
Coerces the input value to a string. Null values and empty strings are mapped to null.

Control Flow Functions

# if(test, thenValue, elseValue)
If test is truthy, returns thenValue. Otherwise, returns elseValue. The if function is equivalent to the ternary operator a ? b : c.

Back to Top

Math Functions

Basic mathematical functions.

# isNaN(value)
Returns true if value is not a number. Same as JavaScript’s isNaN.

# isFinite(value)
Returns true if value is a finite number. Same as JavaScript’s isFinite.

# abs(value)
Returns the absolute value of value. Same as JavaScript’s Math.abs.

# acos(value)
Trigonometric arccosine. Same as JavaScript’s Math.acos.

# asin(value)
Trigonometric arcsine. Same as JavaScript’s Math.asin.

# atan(value)
Trigonometric arctangent. Same as JavaScript’s Math.atan.

# atan2(dy, dx)
Returns the arctangent of dy / dx. Same as JavaScript’s Math.atan2.

# ceil(value)
Rounds value to the nearest integer of equal or greater value. Same as JavaScript’s Math.ceil.

# cos(value)
Trigonometric cosine. Same as JavaScript’s Math.cos.

# exp(exponent)
Returns the value of e raised to the provided exponent. Same as JavaScript’s Math.exp.

# floor(value)
Rounds value to the nearest integer of equal or lower value. Same as JavaScript’s Math.floor.

# log(value)
Returns the natural logarithm of value. Same as JavaScript’s Math.log.

# max(value1, value2, …)
Returns the maximum argument value. Same as JavaScript’s Math.max.

# min(value1, value2, …)
Returns the minimum argument value. Same as JavaScript’s Math.min.

# pow(value, exponent)
Returns value raised to the given exponent. Same as JavaScript’s Math.pow.

# random()
Returns a pseudo-random number in the range [0,1). Same as JavaScript’s Math.random.

# round(value)
Rounds value to the nearest integer. Same as JavaScript’s Math.round.

# sin(value)
Trigonometric sine. Same as JavaScript’s Math.sin.

# sqrt(value)
Square root function. Same as JavaScript’s Math.sqrt.

# tan(value)
Trigonometric tangent. Same as JavaScript’s Math.tan.

# clamp(value, min, max)
Restricts value to be between the specified min and max.

Back to Top

Date/Time Functions

Functions for working with date/time values.

# now()
Returns the timestamp for the current time.

# datetime(year, month[, day, hour, min, sec, millisec])
Returns a new Date instance. The month is 0-based, such that 1 represents February.

# date(datetime)
Returns the day of the month for the given datetime value, in local time.

# day(datetime)
Returns the day of the week for the given datetime value, in local time.

# year(datetime)
Returns the year for the given datetime value, in local time.

# quarter(datetime)
Returns the quarter of the year (0-3) for the given datetime value, in local time.

# month(datetime)
Returns the (zero-based) month for the given datetime value, in local time.

# hours(datetime)
Returns the hours component for the given datetime value, in local time.

# minutes(datetime)
Returns the minutes component for the given datetime value, in local time.

# seconds(datetime)
Returns the seconds component for the given datetime value, in local time.

# milliseconds(datetime)
Returns the milliseconds component for the given datetime value, in local time.

# time(datetime)
Returns the epoch-based timestamp for the given datetime value.

# timezoneoffset(datetime)
Returns the timezone offset from the local timezone to UTC for the given datetime value.

# utc(year, month[, day, hour, min, sec, millisec])
Returns a timestamp for the given UTC date. The month is 0-based, such that 1 represents February.

# utcdate(datetime)
Returns the day of the month for the given datetime value, in UTC time.

# utcday(datetime)
Returns the day of the week for the given datetime value, in UTC time.

# utcyear(datetime)
Returns the year for the given datetime value, in UTC time.

# utcquarter(datetime)
Returns the quarter of the year (0-3) for the given datetime value, in UTC time.

# utcmonth(datetime)
Returns the (zero-based) month for the given datetime value, in UTC time.

# utchours(datetime)
Returns the hours component for the given datetime value, in UTC time.

# utcminutes(datetime)
Returns the minutes component for the given datetime value, in UTC time.

# utcseconds(datetime)
Returns the seconds component for the given datetime value, in UTC time.

# utcmilliseconds(datetime)
Returns the milliseconds component for the given datetime value, in UTC time.

Back to Top

Array Functions

Functions for working with arrays of values.

# clamprange(range, min, max)
Clamps a two-element range array in a span-preserving manner. If the span of the input range is less than (max - min) and an endpoint exceeds either the min or max value, the range is translated such that the span is preserved and one endpoint touches the boundary of the [min, max] range. If the span exceeds (max - min), the range [min, max] is returned.

# indexof(array, value)
Returns the first index of value in the input array.

# inrange(value, range)
Tests whether value lies within (or is equal to either) the first and last values of the range array.

# lastindexof(array)
Returns the last index of value in the input array.

# length(array)
Returns the length of the input array.

# peek(array)
Returns the last element in the input array. Similar to the built-in Array.pop method, except that it does not remove the last element. This method is a convenient shorthand for array[array.length - 1].

# sequence([start, ]stop[, step])
Returns an array containing an arithmetic sequence of numbers. If step is omitted, it defaults to 1. If start is omitted, it defaults to 0. The stop value is exclusive; it is not included in the result. If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. If the returned array would contain an infinite number of values, an empty range is returned. The arguments are not required to be integers.

# slice(array, start[, end])
Returns a section of array between the start and end indices. If the end argument is negative, it is treated as an offset from the end of the array (length(array) + end).

# span(array)
Returns the span of array: the difference between the last and first elements, or array[array.length-1] - array[0].

Back to Top

String Functions

Functions for modifying text strings.

# indexof(string, substring)
Returns the first index of substring in the input string.

# lastindexof(string, substring)
Returns the last index of substring in the input string.

# length(string)
Returns the length of the input string.

# lower(string)
Transforms string to lower-case letters.

# pad(string, length[, character, align])
Pads a string value with repeated instances of a character up to a specified length. If character is not specified, a space (‘ ‘) is used. By default, padding is added to the end of a string. An optional align parameter specifies if padding should be added to the 'left' (beginning), 'center', or 'right' (end) of the input string.

# parseFloat(string)
Parses the input string to a floating-point value. Same as JavaScript’s parseFloat.

# parseInt(string)
Parses the input string to an integer value. Same as JavaScript’s parseInt.

# replace(string, pattern, replacement)
Returns a new string with some or all matches of pattern replaced by a replacement string. The pattern can be a string or a regular expression. If pattern is a string, only the first instance will be replaced. Same as JavaScript’s String.replace.

# slice(string, start[, end])
Returns a section of string between the start and end indices. If the end argument is negative, it is treated as an offset from the end of the string (length(string) + end).

# substring(string, start[, end])
Returns a section of string between the start and end indices.

# truncate(string, length[, align, ellipsis])
Truncates an input string to a target length. The optional align argument indicates what part of the string should be truncated: 'left' (the beginning), 'center', or 'right' (the end). By default, the 'right' end of the string is truncated. The optional ellipsis argument indicates the string to use to indicate truncated content; by default the ellipsis character (\u2026) is used.

# upper(string)
Transforms string to upper-case letters.

Back to Top

Formatting Functions

Functions for formatting number and datetime values as strings.

# dayFormat(day)
Formats a (0-6) weekday number as a full week day name, according to the current locale. For example: dayFormat(0) -> "Sunday".

# dayAbbrevFormat(day)
Formats a (0-6) weekday number as an abbreviated week day name, according to the current locale. For example: dayAbbrevFormat(0) -> "Sun".

# format(value, specifier)
Formats a numeric value as a string. The specifier must be a valid d3-format specifier (e.g., format(value, ',.2f').

# monthFormat(month)
Formats a (zero-based) month number as a full month name, according to the current locale. For example: monthFormat(0) -> "January".

# monthAbbrevFormat(month)
Formats a (zero-based) month number as an abbreviated month name, according to the current locale. For example: monthAbbrevFormat(0) -> "Jan".

# timeFormat(value, specifier)
Formats a datetime value (either a Date object or timestamp) as a string, according to the local time. The specifier must be a valid d3-time-format specifier. For example: timeFormat(timestamp, '%A').

# timeParse(string, specifier)
Parses a string value to a Date object, according to the local time. The specifier must be a valid d3-time-format specifier. For example: timeParse('June 30, 2015', '%B %d, %Y').

# utcFormat(value, specifier)
Formats a datetime value (either a Date object or timestamp) as a string, according to UTC time. The specifier must be a valid d3-time-format specifier. For example: utcFormat(timestamp, '%A').

# utcParse(value, specifier)
Parses a string value to a Date object, according to UTC time. The specifier must be a valid d3-time-format specifier. For example: utcParse('June 30, 2015', '%B %d, %Y').

Back to Top

RegExp Functions

Functions for creating and applying regular expressions.

# regexp(pattern[, flags]) - Creates a regular expression instance from an input pattern string and optional flags. Same as JavaScript’s RegExp.

# test(regexp[, string]) - Evaluates a regular expression regexp against the input string, returning true if the string matches the pattern, false otherwise. For example: test(/\\d{3}/, "32-21-9483") -> true.

Back to Top

Color Functions

Functions for representing colors in various color spaces. Color functions return objects that, when coerced to a string, map to valid CSS RGB colors.

# rgb(r, g, b[, opacity]) | rgb(specifier)
Constructs a new RGB color. If r, g and b are specified, these represent the channel values of the returned color; an opacity may also be specified. If a CSS Color Module Level 3 specifier string is specified, it is parsed and then converted to the RGB color space. Uses d3-color’s rgb function.

# hsl(h, s, l[, opacity]) | hsl(specifier)
Constructs a new HSL color. If h, s and l are specified, these represent the channel values of the returned color; an opacity may also be specified. If a CSS Color Module Level 3 specifier string is specified, it is parsed and then converted to the HSL color space. Uses d3-color’s hsl function.

# lab(l, a, b[, opacity]) | lab(specifier)
Constructs a new CIE LAB color. If l, a and b are specified, these represent the channel values of the returned color; an opacity may also be specified. If a CSS Color Module Level 3 specifier string is specified, it is parsed and then converted to the LAB color space. Uses d3-color’s lab function.

# hcl(h, c, l[, opacity]) | hcl(specifier)
Constructs a new HCL (hue, chroma, luminance) color. If h, c and l are specified, these represent the channel values of the returned color; an opacity may also be specified. If a CSS Color Module Level 3 specifier string is specified, it is parsed and then converted to the HCL color space. Uses d3-color’s hcl function.

Back to Top

Event Functions

Functions for processing input event data. These functions are only legal in expressions evaluated in response to an event (for example a signal event handler). Invoking these functions elsewhere can result in errors.

# item()
Returns the current scenegraph item that is the target of the event.

# group([name])
Returns the scenegraph group mark item in which the current event has occurred. If no arguments are provided, the immediate parent group is returned. If a group name is provided, the matching ancestor group item is returned.

# xy([item])
Returns the x- and y-coordinates for the current event as a two-element array. If no arguments are provided, the top-level coordinate space of the view is used. If a scenegraph item (or string group name) is provided, the coordinate space of the group item is used.

# x([item])
Returns the x coordinate for the current event. If no arguments are provided, the top-level coordinate space of the view is used. If a scenegraph item (or string group name) is provided, the coordinate space of the group item is used.

# y([item])
Returns the y coordinate for the current event. If no arguments are provided, the top-level coordinate space of the view is used. If a scenegraph item (or string group name) is provided, the coordinate space of the group item is used.

# pinchDistance(event)
Returns the pixel distance between the first two touch points of a multi-touch event.

# pinchAngle(event)
Returns the angle of the line connecting the first two touch points of a multi-touch event.

# inScope(item)
Returns true if the given scenegraph item is a descendant of the group mark in which the event handler was defined, false otherwise.

Back to Top

Data Functions

Functions for accessing Vega data sets.

# data(name)
Returns the array of data objects for the Vega data set with the given name. If the data set is not found, returns an empty array.

# indata(name, field, value)
Tests if the data set with a given name contains a datum with a field value that matches the input value. For example: indata('table', 'category', value).

Back to Top

Scale and Projection Functions

Functions for working with Vega scale transforms and cartographic projections.

# scale(name, value[, group])
Applies the named scale transform (or projection) to the specified value. The optional group argument takes a scenegraph group mark item to indicate the specific scope in which to look up the scale or projection.

# invert(name, value[, group])
Inverts the named scale transform (or projection) for the specified value. The optional group argument takes a scenegraph group mark item to indicate the specific scope in which to look up the scale or projection.

# copy(name[, group])
Returns a copy (a new cloned instance) of the named scale transform of projection, or undefined if no scale or projection is found. The optional group argument takes a scenegraph group mark item to indicate the specific scope in which to look up the scale or projection.

# domain(name[, group])
Returns the scale domain array for the named scale transform, or an empty array if the scale is not found. The optional group argument takes a scenegraph group mark item to indicate the specific scope in which to look up the scale.

# range(name[, group])
Returns the scale range array for the named scale transform, or an empty array if the scale is not found. The optional group argument takes a scenegraph group mark item to indicate the specific scope in which to look up the scale.

# bandwidth(name[, group])
Returns the current band width for the named band scale transform, or zero if the scale is not found or is not a band scale. The optional group argument takes a scenegraph group mark item to indicate the specific scope in which to look up the scale.

# bandspace(count[, paddingInner, paddingOuter])
Returns the number of steps needed within a band scale, based on the count of domain elements and the inner and outer padding values. While normally calculated within the scale itself, this function can be helpful for determining the size of a chart’s layout.

# gradient(name, p0, p1[, count])
Returns a linear color gradient for the named scale and starting and ending points p0 and p1 (each an [x, y] array). The optional count argument indicates a desired target number of color stops to use in the gradient.

# panLinear(domain, delta)
Given a linear scale domain array with numeric or datetime values, returns a new two-element domain array that is the result of panning the domain by a fractional delta. The delta value represents fractional units of the scale range; for example, 0.5 indicates panning the scale domain to the right by half the scale range.

# panLog(domain, delta)
Given a log scale domain array with numeric or datetime values, returns a new two-element domain array that is the result of panning the domain by a fractional delta. The delta value represents fractional units of the scale range; for example, 0.5 indicates panning the scale domain to the right by half the scale range.

# panPow(domain, delta, exponent)
Given a power scale domain array with numeric or datetime values and the given exponent, returns a new two-element domain array that is the result of panning the domain by a fractional delta. The delta value represents fractional units of the scale range; for example, 0.5 indicates panning the scale domain to the right by half the scale range.

# zoomLinear(domain, anchor, scaleFactor)
Given a linear scale domain array with numeric or datetime values, returns a new two-element domain array that is the result of zooming the domain by a scaleFactor, centered at the provided fractional anchor. The anchor value represents the zoom position in terms of fractional units of the scale range; for example, 0.5 indicates a zoom centered on the mid-point of the scale range.

# zoomLog(domain, anchor, scaleFactor)
Given a log scale domain array with numeric or datetime values, returns a new two-element domain array that is the result of zooming the domain by a scaleFactor, centered at the provided fractional anchor. The anchor value represents the zoom position in terms of fractional units of the scale range; for example, 0.5 indicates a zoom centered on the mid-point of the scale range.

# zoomPow(domain, anchor, scaleFactor, exponent)
Given a power scale domain array with numeric or datetime values and the given exponent, returns a new two-element domain array that is the result of zooming the domain by a scaleFactor, centered at the provided fractional anchor. The anchor value represents the zoom position in terms of fractional units of the scale range; for example, 0.5 indicates a zoom centered on the mid-point of the scale range.

Back to Top

Geographic Functions

Functions for analyzing geographic regions represented as GeoJSON features.

# geoArea(projection, feature[, group)
Returns the projected planar area (typically in square pixels) of a GeoJSON feature according to the named projection. The optional group argument takes a scenegraph group mark item to indicate the specific scope in which to look up the projection. Uses d3-geo’s path.area.

# geoBounds(projection, feature[, group)
Returns the projected planar bounding box (typically in pixels) for the specified GeoJSON feature, according to the named projection. The bounding box is represented by a two-dimensional array: [[x₀, y₀], [x₁, y₁]], where x₀ is the minimum x-coordinate, y₀ is the minimum y-coordinate, x₁ is the maximum x-coordinate, and y₁ is the maximum y-coordinate. The optional group argument takes a scenegraph group mark item to indicate the specific scope in which to look up the projection. Uses d3-geo’s path.bounds.

# geoCentroid(projection, feature[, group)
Returns the projected planar centroid (typically in pixels) for the specified GeoJSON feature, according to the named projection. The optional group argument takes a scenegraph group mark item to indicate the specific scope in which to look up the projection. Uses d3-geo’s path.centroid.

Back to Top

Tree (Hierarchy) Functions

Functions for processing hierarchy data sets constructed with the stratify or nest transforms.

# treePath(name, source, target)
For the hierarchy data set with the given name, returns the shortest path through from the source node id to the target node id. The path starts at the source node, ascends to the least common ancestor of the source node and the target node, and then descends to the target node.

# treeAncestors(name, node)
For the hierarchy data set with the given name, returns the array of ancestors nodes, starting with the input node, then followed by each parent up to the root.

Back to Top

Browser Functions

Functions for accessing web browser facilities.

# containerSize()
Returns the current CSS box size ([el.clientWidth, el.clientHeight]) of the parent DOM element that contains the Vega view. If there is no container element, returns [undefined, undefined].

# screen()
Returns the window.screen object, or {} if Vega is not running in a browser environment.

# windowSize()
Returns the current window size ([window.innerWidth, window.innerHeight]) or [undefined, undefined] if Vega is not running in a browser environment.

Back to Top

Logging Functions

Logging functions for writing messages to the console. These can be helpful when debugging expressions.

# warn(value1[, value2, …])
Logs a warning message and returns the last argument. For the message to appear in the console, the visualization view must have the appropriate logging level set.

# info(value1[, value2, …])
Logs an informative message and returns the last argument. For the message to appear in the console, the visualization view must have the appropriate logging level set.

# debug(value1[, value2, …])
Logs a debugging message and returns the last argument. For the message to appear in the console, the visualization view must have the appropriate logging level set.

Back to Top