To enable custom calculations, Vega includes its ownexpression language for writing basic formulas. For example, these expressions are used by thefilter andformula transforms to modify data, and withinsignal 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 specialif(test, thenValue, elseValue)
function are supported.
To keep the expression language simple, secure and free of unwanted side effects, the following elements arenot 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 – is provided by thevega-expression module.
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
ordatum['My Value']
.
#event
If the expression is being invoked in response to an event, anevent variable is defined. This variable consists of a standard JavaScript DOM event, providing access to bound properties of the event, such asevent.metaKey
orevent.keyCode
.
#signal names
Any in-scope signal value can be referenced directly by name. For example, if you have defined a signal namedhover
within your Vega specification, you can refer to it directly within an expression (e.g.,hover.value
). Similarly, to lookup an object property whose name is bound to the signalproperty_name
, you could usedatum[property_name]
.
Constant values that can be referenced by name within expressions.
#NaN
Not a number. Same as the JavaScript literalNaN
.
#E
The transcendental numbere. Same as JavaScript’sMath.E
.
#LN2
The natural log of 2. Same as JavaScript’sMath.LN2
.
#LN10
The natural log of 10. Same as JavaScript’sMath.LN10
.
#LOG2E
The base 2 logarithm ofe. Same as JavaScript’sMath.LOG2E
.
#LOG10E
The base 10 logarithme. Same as JavaScript’sMath.LOG10E
.
#MAX_VALUE
The largest positive numeric value. Same as JavaScript’sNumber.MAX_VALUE
.
#MIN_VALUE
The smallest positive numeric value. Same as JavaScript’sNumber.MIN_VALUE
.
#PI
The transcendental numberπ. Same as JavaScript’sMath.PI
.
#SQRT1_2
The square root of 0.5. Same as JavaScript’sMath.SQRT1_2
.
#SQRT2
The square root of 2. Same as JavaScript’sMath.SQRT2
.
Predicate functions for checking value types.
#isArray(value)
Returns true ifvalue is an array, false otherwise.
#isBoolean(value)
Returns true ifvalue is a boolean (true
orfalse
), false otherwise.
#isDate(value)
Returns true ifvalue is a Date object, false otherwise. This method will return false for timestamp numbers or date-formatted strings; it recognizes Date objects only.
#isDefined(value)≥ 5.4
Returns true ifvalue is a defined value, false ifvalue equalsundefined
. This method will return true fornull
andNaN
values.
#isNumber(value)
Returns true ifvalue is a number, false otherwise.NaN
andInfinity
are considered numbers.
#isObject(value)
Returns true ifvalue is an object (including arrays and Dates), false otherwise.
#isRegExp(value)
Returns true ifvalue is a RegExp (regular expression) object, false otherwise.
#isString(value)
Returns true ifvalue is a string, false otherwise.
#isValid(value)≥ 5.4
Returns true ifvalue is notnull
,undefined
, orNaN
, false otherwise.
Functions for coercing values to a desired type.
#toBoolean(value)
Coerces the inputvalue to a string. Null values and empty strings are mapped tonull
.
#toDate(value)
Coerces the inputvalue to a Date instance. Null values and empty strings are mapped tonull
. If an optionalparser function is provided, it is used to perform date parsing, otherwiseDate.parse
is used. Be aware thatDate.parse
has different implementations across browsers!
#toNumber(value)
Coerces the inputvalue to a number. Null values and empty strings are mapped tonull
.
#toString(value)
Coerces the inputvalue to a string. Null values and empty strings are mapped tonull
.
#if(test,thenValue,elseValue)
Iftest is truthy, returnsthenValue. Otherwise, returnselseValue. Theif function is equivalent to the ternary operatora ? b : c
.
Basic mathematical functions.
#isNaN(value)
Returns true ifvalue is not a number. Same as JavaScript’sNumber.isNaN
.
#isFinite(value)
Returns true ifvalue is a finite number. Same as JavaScript’sNumber.isFinite
.
#abs(value)
Returns the absolute value ofvalue. Same as JavaScript’sMath.abs
.
#acos(value)
Trigonometric arccosine. Same as JavaScript’sMath.acos
.
#asin(value)
Trigonometric arcsine. Same as JavaScript’sMath.asin
.
#atan(value)
Trigonometric arctangent. Same as JavaScript’sMath.atan
.
#atan2(dy,dx)
Returns the arctangent ofdy / dx. Same as JavaScript’sMath.atan2
.
#ceil(value)
Roundsvalue to the nearest integer of equal or greater value. Same as JavaScript’sMath.ceil
.
#clamp(value,min,max)
Restrictsvalue to be between the specifiedmin andmax.
#cos(value)
Trigonometric cosine. Same as JavaScript’sMath.cos
.
#exp(exponent)
Returns the value ofe raised to the providedexponent. Same as JavaScript’sMath.exp
.
#floor(value)
Roundsvalue to the nearest integer of equal or lower value. Same as JavaScript’sMath.floor
.
#hypot(value)
Returns the square root of the sum of squares of its arguments. Same as JavaScript’sMath.hypot
.
#log(value)
Returns the natural logarithm ofvalue. Same as JavaScript’sMath.log
.
#max(value1,value2, …)
Returns the maximum argument value. Same as JavaScript’sMath.max
.
#min(value1,value2, …)
Returns the minimum argument value. Same as JavaScript’sMath.min
.
#pow(value,exponent)
Returnsvalue raised to the givenexponent. Same as JavaScript’sMath.pow
.
#random()
Returns a pseudo-random number in the range [0,1). Same as JavaScript’sMath.random
.
#round(value)
Roundsvalue to the nearest integer. Same as JavaScript’sMath.round
.
#sin(value)
Trigonometric sine. Same as JavaScript’sMath.sin
.
#sqrt(value)
Square root function. Same as JavaScript’sMath.sqrt
.
#tan(value)
Trigonometric tangent. Same as JavaScript’sMath.tan
.
Methods for sampling and calculating values for probability distributions.
#sampleNormal([mean,stdev])≥ 5.7
Returns a sample from a univariatenormal (Gaussian) probability distribution with specifiedmean and standard deviationstdev. If unspecified, the mean defaults to0
and the standard deviation defaults to1
.
#cumulativeNormal(value[,mean,stdev])≥ 5.7
Returns the value of thecumulative distribution function at the given input domainvalue for a normal distribution with specifiedmean and standard deviationstdev. If unspecified, the mean defaults to0
and the standard deviation defaults to1
.
#densityNormal(value[,mean,stdev])≥ 5.7
Returns the value of theprobability density function at the given input domainvalue, for a normal distribution with specifiedmean and standard deviationstdev. If unspecified, the mean defaults to0
and the standard deviation defaults to1
.
#quantileNormal(probability[,mean,stdev])≥ 5.7
Returns the quantile value (the inverse of thecumulative distribution function) for the given inputprobability, for a normal distribution with specifiedmean and standard deviationstdev. If unspecified, the mean defaults to0
and the standard deviation defaults to1
.
#sampleLogNormal([mean,stdev])≥ 5.7
Returns a sample from a univariatelog-normal probability distribution with specified logmean and log standard deviationstdev. If unspecified, the log mean defaults to0
and the log standard deviation defaults to1
.
#cumulativeLogNormal(value[,mean,stdev])≥ 5.7
Returns the value of thecumulative distribution function at the given input domainvalue for a log-normal distribution with specified logmean and log standard deviationstdev. If unspecified, the log mean defaults to0
and the log standard deviation defaults to1
.
#densityLogNormal(value[,mean,stdev])≥ 5.7
Returns the value of theprobability density function at the given input domainvalue, for a log-normal distribution with specified logmean and log standard deviationstdev. If unspecified, the log mean defaults to0
and the log standard deviation defaults to1
.
#quantileLogNormal(probability[,mean,stdev])≥ 5.7
Returns the quantile value (the inverse of thecumulative distribution function) for the given inputprobability, for a log-normal distribution with specified logmean and log standard deviationstdev. If unspecified, the log mean defaults to0
and the log standard deviation defaults to1
.
#sampleUniform([min,max])≥ 5.7
Returns a sample from a univariatecontinuous uniform probability distribution over the interval [min,max). If unspecified,min defaults to0
andmax defaults to1
. If only one argument is provided, it is interpreted as themax value.
#cumulativeUniform(value[,min,max])≥ 5.7
Returns the value of thecumulative distribution function at the given input domainvalue for a uniform distribution over the interval [min,max). If unspecified,min defaults to0
andmax defaults to1
. If only one argument is provided, it is interpreted as themax value.
#densityUniform(value[,min,max])≥ 5.7
Returns the value of theprobability density function at the given input domainvalue, for a uniform distribution over the interval [min,max). If unspecified,min defaults to0
andmax defaults to1
. If only one argument is provided, it is interpreted as themax value.
#quantileUniform(probability[,min,max])≥ 5.7
Returns the quantile value (the inverse of thecumulative distribution function) for the given inputprobability, for a uniform distribution over the interval [min,max). If unspecified,min defaults to0
andmax defaults to1
. If only one argument is provided, it is interpreted as themax value.
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 newDate
instance. Themonth is 0-based, such that1
represents February.
#date(datetime)
Returns the day of the month for the givendatetime value, in local time.
#day(datetime)
Returns the day of the week for the givendatetime value, in local time.
#dayofyear(datetime)≥ 5.11
Returns the one-based day of the year for the givendatetime value, in local time.
#year(datetime)
Returns the year for the givendatetime value, in local time.
#quarter(datetime)
Returns the quarter of the year (0-3) for the givendatetime value, in local time.
#month(datetime)
Returns the (zero-based) month for the givendatetime value, in local time.
#week(date)≥ 5.11
Returns the week number of the year for the givendatetime, in local time. This function assumes Sunday-based weeks. Days before the first Sunday of the year are considered to be in week 0, the first Sunday of the year is the start of week 1, the second Sunday week 2,etc..
#hours(datetime)
Returns the hours component for the givendatetime value, in local time.
#minutes(datetime)
Returns the minutes component for the givendatetime value, in local time.
#seconds(datetime)
Returns the seconds component for the givendatetime value, in local time.
#milliseconds(datetime)
Returns the milliseconds component for the givendatetime value, in local time.
#time(datetime)
Returns the epoch-based timestamp for the givendatetime value.
#timezoneoffset(datetime)
Returns the timezone offset from the local timezone to UTC for the givendatetime value.
#timeOffset(unit,date[,step])≥ 5.8
Returns a newDate
instance that offsets the givendate by the specified timeunit in the local timezone. The optionalstep argument indicates the number of time unit steps to offset by (default 1).
#timeSequence(unit,start,stop[,step])≥ 5.8
Returns an array ofDate
instances fromstart (inclusive) tostop (exclusive), with each entry separated by the given timeunit in the local timezone. The optionalstep argument indicates the number of time unit steps to take between each sequence entry (default 1).
#utc(year,month[,day,hour,min,sec,millisec])
Returns a timestamp for the given UTC date. Themonth is 0-based, such that1
represents February.
#utcdate(datetime)
Returns the day of the month for the givendatetime value, in UTC time.
#utcday(datetime)
Returns the day of the week for the givendatetime value, in UTC time.
#utcdayofyear(datetime)≥ 5.11
Returns the one-based day of the year for the givendatetime value, in UTC time.
#utcyear(datetime)
Returns the year for the givendatetime value, in UTC time.
#utcquarter(datetime)
Returns the quarter of the year (0-3) for the givendatetime value, in UTC time.
#utcmonth(datetime)
Returns the (zero-based) month for the givendatetime value, in UTC time.
#utcweek(date)≥ 5.11
Returns the week number of the year for the givendatetime, in UTC time. This function assumes Sunday-based weeks. Days before the first Sunday of the year are considered to be in week 0, the first Sunday of the year is the start of week 1, the second Sunday week 2,etc..
#utchours(datetime)
Returns the hours component for the givendatetime value, in UTC time.
#utcminutes(datetime)
Returns the minutes component for the givendatetime value, in UTC time.
#utcseconds(datetime)
Returns the seconds component for the givendatetime value, in UTC time.
#utcmilliseconds(datetime)
Returns the milliseconds component for the givendatetime value, in UTC time.
#utcOffset(unit,date[,step])≥ 5.8
Returns a newDate
instance that offsets the givendate by the specified timeunit in UTC time. The optionalstep argument indicates the number of time unit steps to offset by (default 1).
#utcSequence(unit,start,stop[,step])≥ 5.8
Returns an array ofDate
instances fromstart (inclusive) tostop (exclusive), with each entry separated by the given timeunit in UTC time. The optionalstep argument indicates the number of time unit steps to take between each sequence entry (default 1).
Functions for working with arrays of values.
#extent(array)≥ 4.0
Returns a new[min, max] array with the minimum and maximum values of the input array, ignoringnull
,undefined
, andNaN
values.
#clampRange(range,min,max)
Clamps a two-elementrange array in a span-preserving manner. If the span of the inputrange is less than(max - min) and an endpoint exceeds either themin ormax 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 ofvalue in the inputarray.
#inrange(value,range)
Tests whethervalue lies within (or is equal to either) the first and last values of therange array.
#join(array[,separator])≥ 5.3
Returns a new string by concatenating all of the elements of the inputarray, separated by commas or a specifiedseparator string.
#lastindexof(array,value)
Returns the last index ofvalue in the inputarray.
#length(array)
Returns the length of the inputarray.
#lerp(array,fraction)
Returns the linearly interpolated value between the first and last entries in thearray for the provided interpolationfraction (typically between 0 and 1). For example,lerp([0, 50], 0.5)
returns 25.
#peek(array)
Returns the last element in the inputarray. Similar to the built-inArray.pop
method, except that it does not remove the last element. This method is a convenient shorthand forarray[array.length - 1]
.
#pluck(array,field)≥ 5.19
Retrieves the value for the specifiedfield from a givenarray of objects. The inputfield string may include nested properties (e.g.,foo.bar.bz
).
#reverse(array)≥ 5.3
Returns a new array with elements in a reverse order of the inputarray. The first array element becomes the last, and the last array element becomes the first.
#sequence([start, ]stop[,step])
Returns an array containing an arithmetic sequence of numbers. Ifstep is omitted, it defaults to 1. Ifstart is omitted, it defaults to 0. Thestop value is exclusive; it is not included in the result. Ifstep is positive, the last element is the largeststart + i * step less thanstop; ifstep is negative, the last element is the smalleststart + i * step greater thanstop. 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 ofarray between thestart andend indices. If theend argument is negative, it is treated as an offset from the end of the array (length(array) + end).
#sort(array)
≥ 5.31
Sorts the array in natural order usingascending from Vega Utils.
#span(array)
Returns the span ofarray: the difference between the last and first elements, orarray[array.length-1] - array[0].
Functions for modifying text strings.
#indexof(string,substring)
Returns the first index ofsubstring in the inputstring.
#lastindexof(string,substring)
Returns the last index ofsubstring in the inputstring.
#length(string)
Returns the length of the inputstring.
#lower(string)
Transformsstring to lower-case letters.
#pad(string,length[,character,align])
Pads astring value with repeated instances of acharacter up to a specifiedlength. Ifcharacter is not specified, a space (‘ ‘) is used. By default, padding is added to the end of a string. An optionalalign parameter specifies if padding should be added to the'left'
(beginning),'center'
, or'right'
(end) of the input string.
#parseFloat(string)
Parses the inputstring to a floating-point value. Same as JavaScript’sparseFloat
.
#parseInt(string)
Parses the inputstring to an integer value. Same as JavaScript’sparseInt
.
#replace(string,pattern,replacement)
Returns a new string with some or all matches ofpattern replaced by areplacement string. Thepattern can be a string or a regular expression. Ifpattern is a string, only the first instance will be replaced. Same asJavaScript’s String.replace.
#slice(string,start[,end])
Returns a section ofstring between thestart andend indices. If theend argument is negative, it is treated as an offset from the end of the string (length(string) + end).
#split(string,separator[,limit])≥ 4.3
Returns an array of tokens created by splitting the inputstring according to a providedseparator pattern. The result can optionally be constrained to return at mostlimit tokens.
#substring(string,start[,end])
Returns a section ofstring between thestart andend indices.
#trim(string)≥ 5.3
Returns a trimmed string with preceding and trailing whitespace removed.
#truncate(string,length[,align,ellipsis])
Truncates an inputstring to a targetlength. The optionalalign 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 optionalellipsis argument indicates the string to use to indicate truncated content; by default the ellipsis character…
(\u2026
) is used.
#upper(string)
Transformsstring to upper-case letters.
#btoa(string)≥ 5.32.0
Creates aBase64-encodedASCII string. Same as JavaScript’sWindow.btoa().
#atob(string)≥ 5.32.0
Decodes anASCII string that was encoded withBase64. Same as JavaScript’sWindow.atob().
Functions for manipulating object instances.
#merge(object1[,object2, …])≥ 4.0
Merges the input objectsobject1,object2, etc into a new output object. Inputs are visited in sequential order, such that key values from later arguments can overwrite those from earlier arguments. Example:merge({a:1, b:2}, {a:3}) -> {a:3, b:2}
.
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 numericvalue as a string. Thespecifier must be a validd3-format specifier (e.g.,format(value, ',.2f')
.Null values are formatted as"null"
.
#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"
.
#timeUnitSpecifier(units[,specifiers])≥ 5.8
Returns a time format specifier string for the given timeunits. The optionalspecifiers object provides a set of specifier sub-strings for customizing the format; for more, see thetimeUnitSpecifier API documentation. The resulting specifier string can then be used as input to thetimeFormat orutcFormat functions, or as theformat parameter of an axis or legend. For example:timeFormat(date, timeUnitSpecifier('year'))
ortimeFormat(date, timeUnitSpecifier(['hours', 'minutes']))
.
#timeFormat(value,specifier)
Formats a datetimevalue (either aDate
object or timestamp) as a string, according to the local time. Thespecifier must be a validd3-time-format specifier orTimeMultiFormat object≥ 5.8. For example:timeFormat(timestamp, '%A')
.Null values are formatted as"null"
.
#timeParse(string,specifier)
Parses astring value to a Date object, according to the local time. Thespecifier must be a validd3-time-format specifier. For example:timeParse('June 30, 2015', '%B %d, %Y')
.
#utcFormat(value,specifier)
Formats a datetimevalue (either aDate
object or timestamp) as a string, according toUTC time. Thespecifier must be a validd3-time-format specifier orTimeMultiFormat object≥ 5.8. For example:utcFormat(timestamp, '%A')
.Null values are formatted as"null"
.
#utcParse(value,specifier)
Parses astring value to a Date object, according toUTC time. Thespecifier must be a validd3-time-format specifier. For example:utcParse('June 30, 2015', '%B %d, %Y')
.
Functions for creating and applying regular expressions.
#regexp(pattern[,flags]) -Creates a regular expression instance from an inputpattern string and optionalflags. Same asJavaScript’sRegExp
.
#test(regexp[,string]) -Evaluates a regular expressionregexp against the inputstring, returningtrue
if the string matches the pattern,false
otherwise. For example:test(/\\d{3}/, "32-21-9483") -> true
.
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 newRGB color. Ifr,g andb are specified, these represent the channel values of the returned color; anopacity may also be specified. If a CSS Color Module Level 3specifier string is specified, it is parsed and then converted to the RGB color space. Usesd3-color’s rgb function.
#hsl(h,s,l[,opacity]) |hsl(specifier)
Constructs a newHSL color. Ifh,s andl are specified, these represent the channel values of the returned color; anopacity may also be specified. If a CSS Color Module Level 3specifier string is specified, it is parsed and then converted to the HSL color space. Usesd3-color’s hsl function.
#lab(l,a,b[,opacity]) |lab(specifier)
Constructs a newCIE LAB color. Ifl,a andb are specified, these represent the channel values of the returned color; anopacity may also be specified. If a CSS Color Module Level 3specifier string is specified, it is parsed and then converted to the LAB color space. Usesd3-color’s lab function.
#hcl(h,c,l[,opacity]) |hcl(specifier)
Constructs a newHCL (hue, chroma, luminance) color. Ifh,c andl are specified, these represent the channel values of the returned color; anopacity may also be specified. If a CSS Color Module Level 3specifier string is specified, it is parsed and then converted to the HCL color space. Usesd3-color’s hcl function.
#luminance(specifier)≥ 5.7
Returns the luminance for the given colorspecifier (compatible withd3-color’s rgb function). The luminance is calculated according to theW3C Web Content Accessibility Guidelines.
#contrast(specifier1, specifier2)≥ 5.7
Returns the contrast ratio between the input color specifiers as a float between 1 and 21. The contrast is calculated according to theW3C Web Content Accessibility Guidelines.
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 scenegraphitem (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 scenegraphitem (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 scenegraphitem (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 scenegraphitem is a descendant of the group mark in which the event handler was defined, false otherwise.
Functions for accessing Vega data sets.
#data(name)
Returns the array of data objects for the Vega data set with the givenname. If the data set is not found, returns an empty array.
#indata(name,field,value)
Tests if the data set with a givenname contains a datum with afield value that matches the inputvalue. For example:indata('table', 'category', value)
.
Functions for working with Vega scale transforms and cartographic projections.
#scale(name,value[,group])
Applies the named scale transform (or projection) to the specifiedvalue. The optionalgroup 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 specifiedvalue. The optionalgroup 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, orundefined
if no scale or projection is found. The optionalgroup 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 optionalgroup 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 optionalgroup 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 optionalgroup 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 thecount 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(scale,p0,p1[,count])
Returns a linear color gradient for thescale (whose range must be acontinuous color scheme) and starting and ending pointsp0 andp1, each an[x, y] array. The pointsp0 andp1 should be expressed in normalized coordinates in the domain [0, 1], relative to the bounds of the item being colored. If unspecified,p0 defaults to[0, 0]
andp1 defaults to[1, 0]
, for a horizontal gradient that spans the full bounds of an item. The optionalcount argument indicates a desired target number of sample points to take from the color scale.
#panLinear(domain,delta)
Given a linear scaledomain array with numeric or datetime values, returns a new two-element domain array that is the result of panning the domain by a fractionaldelta. Thedelta 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 scaledomain array with numeric or datetime values, returns a new two-element domain array that is the result of panning the domain by a fractionaldelta. Thedelta 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 scaledomain array with numeric or datetime values and the givenexponent, returns a new two-element domain array that is the result of panning the domain by a fractionaldelta. Thedelta 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.
#panSymlog(domain,delta,constant)
Given a symmetric log scaledomain array with numeric or datetime values parameterized by the givenconstant, returns a new two-element domain array that is the result of panning the domain by a fractionaldelta. Thedelta 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 scaledomain array with numeric or datetime values, returns a new two-element domain array that is the result of zooming the domain by ascaleFactor, centered at the provided fractionalanchor. Theanchor 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 scaledomain array with numeric or datetime values, returns a new two-element domain array that is the result of zooming the domain by ascaleFactor, centered at the provided fractionalanchor. Theanchor 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 scaledomain array with numeric or datetime values and the givenexponent, returns a new two-element domain array that is the result of zooming the domain by ascaleFactor, centered at the provided fractionalanchor. Theanchor 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.
#zoomSymlog(domain,anchor,scaleFactor,constant)
Given a symmetric log scaledomain array with numeric or datetime values parameterized by the givenconstant, returns a new two-element domain array that is the result of zooming the domain by ascaleFactor, centered at the provided fractionalanchor. Theanchor 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.
Functions for analyzing geographic regions represented as GeoJSON features.
#geoArea(projection,feature[,group])
Returns the projected planar area (typically in square pixels) of a GeoJSONfeature according to the namedprojection. If theprojection argument isnull
, computes the spherical area in steradians using unprojected longitude, latitude coordinates. The optionalgroup argument takes a scenegraph group mark item to indicate the specific scope in which to look up the projection. Uses d3-geo’sgeoArea andpath.area methods.
#geoBounds(projection,feature[,group])
Returns the projected planar bounding box (typically in pixels) for the specified GeoJSONfeature, according to the namedprojection. The bounding box is represented by a two-dimensional array: [[x₀,y₀], [x₁,y₁]], wherex₀ is the minimum x-coordinate,y₀ is the minimum y-coordinate,x₁ is the maximum x-coordinate, andy₁ is the maximum y-coordinate. If theprojection argument isnull
, computes the spherical bounding box using unprojected longitude, latitude coordinates. The optionalgroup argument takes a scenegraph group mark item to indicate the specific scope in which to look up the projection. Uses d3-geo’sgeoBounds andpath.bounds methods.
#geoCentroid(projection,feature[,group])
Returns the projected planar centroid (typically in pixels) for the specified GeoJSONfeature, according to the namedprojection. If theprojection argument isnull
, computes the spherical centroid using unprojected longitude, latitude coordinates. The optionalgroup argument takes a scenegraph group mark item to indicate the specific scope in which to look up the projection. Uses d3-geo’sgeoCentroid andpath.centroid methods.
#geoScale(projection[,group])
Returns the scale value for the namedprojection. The optionalgroup argument takes a scenegraph group mark item to indicate the specific scope in which to look up the projection.
Functions for processing hierarchy data sets constructed with thestratify ornest transforms.
#treePath(name,source,target)
For the hierarchy data set with the givenname, returns the shortest path through from thesource node id to thetarget node id. The path starts at thesource node, ascends to the least common ancestor of thesource node and thetarget node, and then descends to thetarget node.
#treeAncestors(name,node)
For the hierarchy data set with the givenname, returns the array of ancestors nodes, starting with the inputnode, then followed by each parent up to the root.
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 thewindow.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.
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.