gicentre/elm-vega/4.0.0

NOTE: the latest version is 5.7.1

Vega

Create full Vega specifications in Elm. The module can generate JSON specs that may be passed to the Vega runtime library to activate the visualization.

Creating A Vega Specification

toVega : List ( VProperty, Spec ) -> Spec

Convert a list of Vega specifications into a single JSON object that may be passed to Vega for graphics generation. Recommended practice for top-level properties that have more than a simple parameter is to create as a series of compactly named functions (e.g. ds for the data source, sc for scales, si for signals, ax for axes etc.) and construct a list of them. For example,

helloWorld : Spec
helloWorld =
    let
        table =
            dataFromColumns "table" []
                << dataColumn "label" (vStrs [ "Hello", "from", "elm-vega" ])
                << dataColumn "x" (vNums [ 1, 2, 3 ])


        ds =
            dataSource [ table [] ]


        sc =
            scales
                << scale "xScale"
                    [ scDomain (doData [ daDataset "table", daField (field "x") ])
                    , scRange RaWidth
                    ]


        mk =
            marks
                << mark text
                    [ mFrom [ srData (str "table") ]
                    , mEncode
                        [ enEnter
                            [ maX [ vScale "xScale", vField (field "x") ]
                            , maText [ vField (field "label") ]
                            ]
                        ]
                    ]
    in
    toVega
        [ width 100, ds, sc [], mk [] ]
combineSpecs : List LabelledSpec -> Spec

Combine a list of labelled specifications into a single specification that may be passed to JavaScript for rendering. Useful for creating a single page with multiple visualizations.

combineSpecs
    [ ( "vis1", myFirstVis )
    , ( "vis2", mySecondVis )
    , ( "vis3", myOtherVis )
    ]

Top-level Vega properties (see the specification documentation).

Data properties specify the input data to be visualized. Generated by dataSource that can collect together data tables such as those read from a URL or generated inline.

Signal properties specify dynamic variables that respond reactively to other signals or interactions. Generated by signals.

Scale properties map data values to visual channels such as position, or color. Generated by scales.

Projection properties specify how geospatial data referenced with longitude, latitude coordinates are projected onto a plane for visualization. Generated by projections.

Axis properties specify how spatial scale mappings are visualized, such as with tick marks, grid lines and labels. Generated by axes.

Legend properties specify how visual scale mappings such as color, shape and size are visualized. Generated by legends.

Title properties specify how a visualization title should appear. Generated by title.

** Layout properties** specify how a group of visual marks are organised within a grid. This allows visualizations to be composed of other visualizations, for example in a dashboard or collection of small multiples. Generated by layout.

Mark properties specify how to visually encode data with graphical primitives such as points, lines and other symbols. Generated by marks.

Top-level group encodings specify the appearance of the chart's data rectangle. For example setting the background color of the plotting area. Generated by encode.

Config properties specify default settings of a specification. Allows consistent and easily modifiable styles to be applied to a visualization. Generated by config.

Supplementary properties add metadata and some styling to one or more visualizations. Generated by width, height, padding, paddings, autosize, background and description.

Passing Values into a Vega Specification

Data types such as numbers, strings and Booleans are generated by functions. For example, expressions generate new values based on operations applied to existing ones; fields reference a column of a data table; signals respond dynamically to data or interaction.

Numbers

num : Float -> Num

A numeric literal.

nums : List Float -> Num

A list of numeric literals. For lists that contain a mixture of numeric literals and signals use numList instead.

numSignal : String -> Num

Numeric value referenced by the value in the named signal.

numSignals : List String -> Num

List of numeric values referenced by the values in the named signals.

An expression that evaluates to a numeric value.

numList : List Num -> Num

List of potentially mixed numeric types. Useful when a domain is specified as being bounded by 0 and some signal:

scDomain (doNums (numList [ num 0, numSignal "mySignal" ]))

An absence of a numeric value.

Strings

str : String -> Str

A string literal.

strs : List String -> Str

A list of string literals.

strSignal : String -> Str

String value referenced by the value in the named signal.

strSignals : List String -> Str

String values referenced by the values in the named signals.

Expression that when evaluated, is a string.

An absence of a string value.

Booleans

A Boolean true value.

A Boolean false value.

boos : List Bool -> Boo

List of Boolean literals.

booSignal : String -> Boo

Name of a signal that will generate a Boolean value.

booSignals : List String -> Boo

List of signals that will generate Boolean values.

Eexpression that when evaluated, will be a Boolean value.

Generic Values

Used by functions that expect values of mixed types.

vNum : Float -> Value

A numeric value.

vNums : List Float -> Value

A list of numbers.

vStr : String -> Value

A string value.

vStrs : List String -> Value

A list of string values.

A 'true' value.

A 'false' value.

vBoos : List Bool -> Value

A list of Boolean values.

vSignal : String -> Value

A named signal.

A data or signal field.

A color value.

Band number or fraction of a band number. Band scales are used when aggregating data into discrete categories such as in a frequency histogram.

vObject : List Value -> Value

Object containing a list of key-value pairs.

keyValue : String -> Value -> Value

Custom key-value pair to be stored in an object generated by vObject.

vValues : List Value -> Value

List of values. Useful for nesting collections of possibly mixed types.

ifElse : String -> List Value -> List Value -> Value

Values conditional on whether an expression (first parameter) evaluates as true. The second and third parameters represent the 'then' and 'else' branches of the test.

To include nested conditions, subsequent ifElse calls should be placed in the 'else' branch.

maFontWeight
    [ ifElse "indata('selected', 'source', datum.id)"
        [ vStr "bold" ]
        [ ifElse "indata('selected', 'target', datum.id)"
            [ vStr "bold" ]
            [ vNull ]
        ]
    ]

An absence of a value.

A multiplication value modifier.

An exponential value modifier.

An additive value modifier.

A rounding value modifier. Rounding is applied after all other modifiers.

vScale : String -> Value

Name of a scale.

A scale field used to dynamically look up a scale name.

Indirect References

See the Vega field value documentation.

field : String -> Field

Name of a field to reference.

fSignal : String -> Field

Field referenced by the value in the named signal.

fExpr : String -> Field

Expression that references a field but can perform calculations on each datum in the field.

fExpr "scale('xScale', datum.Horsepower)"

Perform a lookup on the current data object using the given field. Once evaluated this is similar to simply providing a string value.

Property of the enclosing group mark instance as a field value.

Field of the enclosing group mark’s data object as a field.

expr : String -> Expr

Expression to enable custom calculations specified in the Vega expression language. In contrast to a field reference or signal, the expression is evaluated once per datum behaving like an anonymous (lambda) function.

exField : String -> Expr

Field lookup that forms a Vega Expr. In contrast to an expression generated by expr, a field lookup is applied once to an entire field rather than evaluated once per datum.

Thematic Data Types

Temporal

A year time unit.

A month time unit.

A week time unit.

A day time unit.

A hour time unit.

A minute time unit.

A second time unit.

A millisecond time unit.

tuSignal : String -> TimeUnit

Time unit referenced by the value in the named signal.

Color

cHCL : List Value -> List Value -> List Value -> ColorValue

Define a color in HCL space (parameters in H - C - L order).

cHSL : List Value -> List Value -> List Value -> ColorValue

Define a color in HSL space (parameters in H - S - L order).

cLAB : List Value -> List Value -> List Value -> ColorValue

Define a color in CIELab space (parameters in L - A - B order).

cRGB : List Value -> List Value -> List Value -> ColorValue

Color in RGB space.

Creating an Input Data Specification

See the Vega data and the Vega data reference documentation.

dataSource : List DataTable -> Data

Data source to be used by a visualization. A data source is a collection of data tables which themselves may be generated inline, loaded from a URL or the result of a transformation.

data : String -> List DataProperty -> DataTable

Declare a named dataset. Depending on the properties provided this may be from an external file, from a named data source or inline literal values.

dataFromColumns : String -> List FormatProperty -> List DataColumn -> DataTable

Declare a data table from a list of column values. Each column contains values of the same type, but types may vary between columns. Columns should all contain the same number of items; if not the dataset will be truncated to the length of the shortest.

The first parameter should be the name given to the data table for later reference. Field formatting specifications can be provided in the second parameter or as an empty list to use the default formatting. The columns are most easily generated with dataColumn.

dataColumn : String -> Value -> List DataColumn -> List DataColumn

Create a column of data. A column has a name and a list of values. The final parameter is the list of any other columns to which this is added.

dataFromRows : String -> List FormatProperty -> List DataRow -> DataTable

Declare a data table from a list of row values. Each row is specified with a list of tuples where the first value is the column name, and the second the column value for that row. Each column can have a value of a different type but you must ensure that when multiple rows are added, they match the types of other values in the same column. Field formatting specifications can be provided in the first parameter or as an empty list to use the default formatting.

Rows are most easily generated with dataRow. If you are creating data inline (as opposed to reading from a file), generally, adding data by column is more efficient and less error-prone.

dataRow : List ( String, Value ) -> List DataRow -> List DataRow

Create a row of data. A row comprises a list of (columnName, value) pairs. The final parameter is the list of any other rows to which this is added.

Data file to be loaded when generating a dataset.

Data format to use when loading or generating a dataset.

Name a data source when generating a dataset.

daSources : List String -> DataProperty

Name a collection of data sources when generating a dataset.

Data value(s) for generating a dataset inline.

daOn : List Trigger -> DataProperty

Updates to insert, remove, and toggle data values, or clear the data in a dataset when trigger conditions are met.

Generate a global sphere dataset.

Reference a dataset with the given name.

Reference a data field with the given value.

Reference a collection of data fields with the given values.

Create a data reference from a list of literals. Useful when combining with data references from existing data streams. For example

scale "myScale"
    [ scDomain
        (doData
            [ daReferences
                [ [ daValues (vNums [ 2, 4 ]) ]
                , [ daDataset "myData", daField (field "myField") ]
                ]
            ]
        )
    ]

Make a data reference with a signal.

Reference a collection of nested data references.

Data Sorting

See the Vega sort and Vega type comparison documentation.

Sort a data reference.

Indicate sorting is to be applied from low to high.

Indicate sorting is to be applied from high to low.

Sorting operation.

Field to be used when sorting.

Sorting type referenced by the value in the named signal.

Indicate ascending order when sorting.

Indicate descending order when sorting.

orderSignal : String -> Order

Sorting order referenced by the value in the named signal.

Data Parsing and Formatting

Indicate a CSV (comma-separated) format when parsing a data source.

Indicate a TSV (tab-separated) format when parsing a data source.

DSV (delimited separated value) format with a custom delimiter.

Indicate a JSON format when parsing a data source.

Property to be extracted from some JSON when it has some surrounding structure or meta-data. e.g., specifying the property values.features is equivalent to retrieving json.values.features from the loaded JSON object with a custom delimiter.

Named property to extract from topoJSON file. Unlike topojsonFeature, geo data are returned as a single unified mesh instance, not as individual GeoJSON features.

TopoJSON feature format. The first parameter is the name of the feature object set to extract.

Format referenced by the value in the named signal (e.g. csv, tsv, json). Useful when dynamic loading of data with different formats is required.

Indicate automatic type inference on data types should be applied when parsing a data source.

parse : List ( String, DataType ) -> FormatProperty

Data parsing rules as a list of tuples where each corresponds to a field name paired with its desired data type. This is only necessary if there is some ambiguity that could prevent correct type inference, such as time text:

dataSource
    [ data "timeData"
        [ daUrl (str "data/timeSeries.json")
        , daFormat [ parse [ ( "timestamp", foDate "%d/%m/%y %H:%M" ) ] ]
        ]
    ]

Specify numeric values are to be parsed when reading input data.

Specify Boolean values are to be parsed when reading input data.

foDate : String -> DataType

Date format for parsing data using D3's formatting specifiers.

foUtc : String -> DataType

UTC date format for parsing data using D3's formatting specifiers.

Transforming Data

Applying a transform to a data stream can filter or generate new fields in the stream, or derive new data streams. Pipe (|>) the stream into the transform function and specify the transform to apply via one or more of these functions. See the Vega transform documentation.

transform : List Transform -> DataTable -> DataTable

Apply the given ordered list of transforms to the given data stream. Transform examples include filtering, creating new data fields from expressions and creating new data fields suitable for a range of visualization and layout types.

Basic Transforms

Aggregation

See the Vega aggregate documentation

Ggroup and summarize an input data stream to produce a derived output stream. Aggregate transforms can be used to compute counts, sums, averages and other descriptive statistics over groups of data objects.

Data fields to group by when performing an aggregation transformation. If not specified, a single group containing all data objects will be used.

Data fields to compute aggregate functions when performing an aggregation transformation. The list of fields should align with the operations and field names provided by agOps and agAs. If no fields and operations are specified, a count aggregation will be used by default.

Aggregation operations to apply to the fields when performing an aggregation transformation. The list of operations should align with the fields output field names provided by agFields and agAs.

agAs : List String -> AggregateProperty

The output field names generated when performing an aggregation transformation. The list of field names should align with the fields operations provided by agFields and agOps. If not provided, automatic names are generated by appending _field to the operation name.

Whether or not the full cross-product of all groupby values should be included in the output of an aggregation transformation.

Whether or not empty (zero count) groups should be dropped when in an aggregation transformation.

Field to act as a unique key when performing an agGroupBy aggregation. This can speed up the aggregation but should only be used when there is redundancy in the list of groupBy fields (as there is when binning for example).

transform
    [ trBin (field "examScore") (nums [ 0, 100 ]) []
    , trAggregate
        [ agKey (field "bin0")
        , agGroupBy [ field "bin0", field "bin1" ]
        , agOps [ Count ]
        , agAs [ "count" ]
        ]
    ]

An input data object containing the maximum field value to be used in an aggregation operation.

An input data object containing the minimum field value to be used in an aggregation operation.

Lower 95% confidence interval to be used in an aggregation operation.

Upper 95% confidence interval to be used in an aggregation operation.

Total count of data objects to be used in an aggregation operation.

Count of distinct data objects to be used in an aggregation operation.

Maximum field value to be used in an aggregation operation.

Mean value to be used in an aggregation operation.

Median field value to be used in an aggregation operation.

Minimum field value to be used in an aggregation operation.

Count of null or undefined field value to be used in an aggregation operation.

Lower quartile boundary of field values to be used in an aggregation operation.

Upper quartile boundary of field values to be used in an aggregation operation.

Standard error of field values to be used in an aggregation operation.

Sample standard deviation of field values to be used in an aggregation operation.

Population standard deviation of field values to be used in an aggregation operation.

Sum of field values to be used in an ggregation operation.

Count of values that are not null, undefined or NaN to be used in an aggregation operation.

Sample variance of field value to be used in an aggregation operation.

Population variance of field value to be used in an aggregation operation.

opSignal : String -> Operation

Aggregation operation referenced by the value in the named signal.

Join Aggregation

See the Vega join aggregation documentation.

Group and summarize an input data stream in a similar way to trAggregate but which is then joined back to the input stream. Helpful for creating derived values that combine both raw data and aggregate calculations, such as percentages of group totals.

Fields to group by in a join aggregate transform.

Fields to aggregate in join aggregate transform.

Operations in a join aggregate transform.

jaAs : List String -> JoinAggregateProperty

Output fields to be generated by a join aggregate transform.

Binning

See the Vega bin documentation

Discretises numeric values into a set of bins. The first parameter is the field to bin, the second a two-element numeric list representing the min/max extent of the bins. Optional binning properties can be provided in the final parameter. Commonly used to create frequency histograms by combining with trAggregate to do the counting of field values in each bin.

transform
    [ trBin (field "examScore") (nums [ 0, 100 ]) []
    , trAggregate
        [ agKey (field "bin0")
        , agGroupBy [ field "bin0", field "bin1" ]
        , agOps [ Count ]
        , agAs [ "count" ]
        ]
    ]

Value in the binned domain at which to anchor the bins of a bin transform, shifting the bin boundaries if necessary to ensure that a boundary aligns with the anchor value. If not specified, the minimum bin extent value serves as the anchor.

Maximum number of bins to create with a bin transform.

Number base to use for automatic bin determination in a bin transform (default is base 100).

Step size to use between bins in a bin transform.

Allowable step sizes between bins to choose from when performing a bin transform.

Minimum allowable bin step size between bins when performing a bin transform.

Allowable bin step sub-divisions when performing a binning transformation. The parameter should evaluate to a list of numeric values. If not specified, the default of [5, 2] is used, which indicates that for base 10 numbers automatic bin determination can consider dividing bin step sizes by 5 and/or 2.

Whether or not the bin boundaries in a binning transform will use human-friendly values such as multiples of ten.

bnSignal : String -> BinProperty

Bind the specification of a binning transform (its start, step and stop properties) to a signal with the given name.

bnAs : String -> String -> BinProperty

Output field names to contain the extent of a binning transform (start and end bin values). If not specified these can be retrieved as bin0 and bin1.

Collection

See the Vega collect documentation.

Collect all the objects in a data stream within a single list, allowing sorting by data field values.

Text Pattern Counting

See the Vega count pattern documentation.

Count the number of occurrences of a text pattern, as defined by a regular expression. This transform will iterate through each data object and count all unique pattern matches found within the designated text field.

The first parameter is the field containing the text to count, the second a list of optional counting properties. The transform generates two fields named text and count unless renamed via cpAs.

Define a match in a count pattern transformation with a regular expression (escaping backslashes):

transform [ trCountPattern (field "data") [ cpPattern (str "[\\w']{3,}") ] ]

Text case transformation to apply before performing a count pattern transformation. The default of Mixedcase will leave text untransformed.

Make text lowercase when pre-processing as part of a count pattern transformation.

Make text uppercase when pre-processing as part of a count pattern transformation.

Leave text unchanged when pre-processing as part of a count pattern transformation.

Define text to ignore in a count pattern transformation with a regular expression (escaping backslashes).

cpAs : String -> String -> CountPatternProperty

Names the two output fields generated by a count pattern transformation. By default they are named text and count.

Cross Product

See the Vega cross-product documentation.

Compute the cross-product of a data stream with itself.

Filter for limiting the results of a cross-product transform.

crAs : String -> String -> CrossProperty

Name the two output fields of a cross-product transform.

Probability Density Function Calculation

See the Vega density documentation.

Compute a new data stream of uniformly-spaced samples drawn from a one-dimensional probability density function (pdf) or cumulative distribution function (cdf). Useful for representing probability distributions and generating continuous distributions from discrete samples through kernel density estimation.

A [min, max] domain from which to sample a distribution in a density transform.

Type of distribution to generate in a density transform.

Probability density function (PDF).

Cumulative density function (CDF).

Density function referenced by the value in the named signal.

Number of uniformly spaced steps to take along an extent domain in a density transform.

dnAs : String -> String -> DensityProperty

Fields to contain a density transform's values (assigned to a new field named in the first parameter) and probabilities (field named in the second parameter). If not specified, the output will allocated to fields named value and probability.

Normal (Gaussian) probability distribution with a given mean (first parameter) and standard deviation (second parameter).

Uniform probability distribution with given minimum (first parameter) and maximum (second parameter) bounds.

diKde : String -> Field -> Num -> Distribution

Kernel density estimate (smoothed probability distribution) for a set of numerical values. The first parameter is the dataset containing the source data, the second the name of the field containing the numerical values and the third the kernel bandwidth. If the bandwidth is 0, it will be estimated from the input data.

Weighted mixture of probability distributions. The parameter should be a list of tuples representing the component distributions and their corresponding weights.

Range calculation

See the Vega extent documentation.

Compute the minimum and maximum values for a data field, producing a two-element [min, max] list.

Compute the minimum and maximum values for a given data field and bind it to a signal with the given name.

Filtering

See the Vega filter and and crossfilter documentation.

Remove objects from a data stream based on the given filter expression.

Maintain a filter mask for multiple dimensional queries, using a set of sorted indices. The parameter is a list of (field,range) pairs indicating which fields to filter and the numeric range of values in the form of a num that should resolve to a [min (inclusive), max (exclusive)] pair.

trCrossFilterAsSignal : List ( Field, Num ) -> String -> Transform

Perform a crossfilter transform. This version can be used with trResolvefilter to enable fast interactive querying over large datasets. The final parameter is the name of a new signal with which to bind the results of the filter (which can then be referenced by trResolveFilter).

Use a filter mask generated by a crossfilter transform to generate filtered data streams efficiently. The first prarameter is the signal created by trCrossFilterAsSignal and the second a bit mask indicating which fields in the crossfilter should be ignored. Each bit corresponds to a field and query in the crossfilter transform’s fields and query lists. If the corresponding bit is on, that field and query will be ignored when resolving the filter. All other queries must pass the filter for a tuple to be included downstream.

Flattening

Map list-valued fields to a set of individual data objects, one per list entry. This version generates the output fields with names corresponding to the list field used.

trFlattenAs : List Field -> List String -> Transform

Similar to trFlatten but allowing the output fields to be named.

Folding and Pivoting

See the Vega fold and pivot documentation.

Collapse one or more data fields into two properties: a key containing the original data field name and a value containing the data value.

trFoldAs : List Field -> String -> String -> Transform

Perform a fold transform generating the key and value fields named by the second and third parameters.

Map unique values from a field to new aggregated fields in the output stream. The first parameter is the field to pivot on (providing new field names). The second is the field containing values to aggregate to populate new values. The third allows the transform to be customised.

Fields to group by when performing a pivot transform. If not specified, a single group containing all data objects will be used.

Maximum number of fields to generate when performing a pivot transform or 0 for no limit.

Aggregation operation to use by when performing a pivot transform. If not specified, fields will be aggregated by their sum.

Deriving New Fields

See the Vega formula, lookup, identifier, project and window documentation.

trFormula : String -> String -> Transform

Extend a data object with new values according to the given Vega expression. The second parameter is a new field name to give the result of the evaluated expression. This version will reapply the formula if the data changes. To perform a one-off formula calculation use trFormulaInitOnly.

dataSource
    [ data "world"
        [ daUrl (str "https://vega.github.io/vega/data/world-110m.json")
        , daFormat [ topojsonFeature "countries" ]
        ]
        |> transform
            [ trFormula "geoCentroid('myProj', datum)" "myCentroid" ]
    ]
trFormulaInitOnly : String -> String -> Transform

Similar to trFormula but will apply the formula only once even if the data changes.

trLookup : String -> Field -> List Field -> List LookupProperty -> Transform

Extend a primary data stream by looking up values on a secondary data stream. The first parameter is the name of the secondary data stream upon which to perform the lookup. The second is the key field in that secondary stream. The third is the set of key fields from the primary data stream, each of which are then searched for in a single key field of the secondary data stream. Optional customisation provided as a list of properties in the final parameter.

luAs : List String -> LookupProperty

Output fields in which to write data found in the secondary stream of a lookup.

Fields to copy from the secondary stream to the primary stream in a lookup transformation. If not specified, a reference to the full data record is copied.

Default value to assign if lookup fails in a lookup transformation.

Extend a data object with a globally unique key value. Identifier values are assigned using an internal counter. This counter is shared across all instances of this transform within a single Vega view, including different data sources, but not across different Vega views.

trProject : List ( Field, String ) -> Transform

Perform a relational algebra projection transform resulting in a new stream of derived data objects that include one or more fields from the input stream. The parameter is a list of field-name pairs where the fields are those fields to be copied over in the projection and the names are the new names to give the projected fields.

Performs calculations such as ranking, lead/lag analysis and running sums over sorted groups of data objects . Calculated values are written back to the input data stream.

transform
    [ trWindow [ wnOperation RowNumber "rank" ]
        [ wnSort [ ( field "myField", Descend ) ] ]
    ]

Aggregate operation to be applied during a window transformation. This version is suitable for operations without parameters (e.g. RowNumber) and that are not applied to a specific field.

The parameters are the operation to apply, the input field (or Nothing if no input field) and the name to give to the field which will contain the results of the calculation.

The example below calculates the average over an unbounded window:

transform
    [ trWindow [ wnAggOperation Mean (Just (field "IMDB_Rating")) "avScore" ]
        [ wnFrame numNull ]
    ]

Window-specific operation to be applied during a window transformation. This version is suitable for operations without parameters (e.g. RowNumber) and that are not applied to a specific field.

The parameters are the operation to apply and the name to give to the field which will contain the results of the calculation.

transform
    [ trWindow [ wnOperation Rank "order" ]
        [ wnSort [ ( field "Gross", Descend ) ] ]
    ]
wnOperationOn : WOperation -> Maybe Num -> Maybe Field -> String -> WindowOperation

Window-specific operation to be applied during a window transformation. This version is suitable for operations that have a parameter (e.g. Lag or Lead) and/or operations that require a specific field as input (e.g. LastValue). The parameters are in order: the type of operation, a possible operation parameter, the field to apply it to and its output field name.

transform
    [ trWindow
        [ wnOperationOn Lag
            (Just (num 5))
            (Just (field "temperature"))
            "oldTemp"
        ]
        []
    ]

Assign consecutive row number to values in a data object to be applied in a window transform.

Rank function to be applied in a window transform.

Dense rank function to be applied in a window transform.

Percentile of values in a sliding window to be applied in a window transform.

Cumulative distribution function to be applied in a window transform.

Value preceding the current object in a sliding window to be applied in a window transform.

Value preceding the current object in a sliding window to be applied in a window transform.

Value following the current object in a sliding window to be applied in a window transform.

First value in a sliding window to be applied in a window transform.

Last value in a sliding window to be applied in a window transform.

Nth value in a sliding window to be applied in a window transform.

woSignal : String -> WOperation

Window operation referenced by the value in the named signal. For names of valid window operations see the Vega window operation documentation

Indicate how sorting data objects is applied within a window transform.

transform
    [ trWindow [ wnOperation RowNumber "order" ]
        [ wnSort [ ( field "score", Ascend ) ] ]
    ]

If two objects are equal in terms of sorting field datum by they are considered 'peers'. If no sorting comparator is specified, data objects are processed in the order they are observed.

Data fields by which to partition data objects into separate windows during a window transform. If not specified, a single group containing all data objects will be used.

Two-element list indicating how a sliding window should proceed during a window transform. The list entries should either be a number indicating the offset from the current data object, or NumNull to indicate unbounded rows preceding or following the current data object.

Whether or not a sliding frame in a window transform should ignore peer values.

Handling Missing Values

See the Vega impute documentation.

Generate new values for missing data. The first parameter is the data field for which missing values should be imputed. The second is a key field that uniquely identifies the data objects within a group and so allows missing values to be identified. The third is a list of optional properties for customising the imputation.

Use minimum of a group when imputing a missing value.

Use maximum of a group when imputing a missing value.

Use the mean value of a group when imputing a missing value.

Use the median value of a group when imputing a missing value.

Use a specific value when imputating a missing value.

Additional collection of key values that should be considered for imputation ] as part of an impute transform.

Imputation method to be used as part of an impute transform. If not specified the default ByMean method will be used.

List of fields by which to group values in an impute transform. Imputation is then performed on a per-group basis, such as a within group mean rather than global mean.

Value to use when an imputation method is set with imByValue in an impute transform.

Sampling

See the Vega sample documentation.

Generate a random sample from a data stream to generate a smaller stream. The parameter determines the maximum number of data items to sample.

Data Generation

See the Vega sequence documentation.

Generate a data stream of numbers between a start (first parameter) and end (second parameter) inclusive in increments specified by the third parameter. If the end value is less than the start value, the third parameter should be negative. The resulting output field will be called data.

Sequences can be used to feed other transforms to generate data to create random (x,y) coordinates:

dataSource
    [ data "randomData" []
        |> transform
            [ trSequence (num 1) (num 1000) (num 1)
            , trFormula "random()" "x"
            , trFormula "random()" "y"
            ]
    ]
trSequenceAs : Num -> Num -> Num -> String -> Transform

Similar to trSequence but allowing the resulting sequence to be named (fourth parameter).

Geographic Transforms

Contouring

See the Vega contour documentation

Generate a set of contour (iso) lines at a set of discrete levels. Commonly used to visualize density estimates for 2D point data.

The first two parameters are the width and height over which to compute the contours. The third a list of optional contour properties. The transform generates a new stream of GeoJSON data as output which may be visualized using either the trGeoShape or trGeoPath transforms.

transform
    [ trContour (numSignal "width")
        (numSignal "height")
        [ cnX (fExpr "scale('xScale', datum.Horsepower)")
        , cnY (fExpr "scale('yScale', datum.Miles_per_Gallon)")
        , cnCount (numSignal "count")
        ]
    ]

Grid of values over which to compute contours. If not provided, trContour will compute contours of the kernel density estimate of input data instead.

X-coordinate field used for density estimation in a contour transformation.

Y-coordinate field used for density estimation in a contour transformation.

Size of cells used for density estimation in a contour transformation.

Kernel density estimation bandwidth used in a contour transformation.

Whether or not contour polygons should be smoothed in a contour transformation. Ignored if kernel density estimation is used.

Explicit contour values to be generated by a contour transformation.

Desired number of contours used in a contour transformation. Ignored if cnThresholds setting explicit contour values are provided.

Whether or not contour threshold values should be automatically aligned to 'nice', human-friendly values when performing a contour transformation.

GeoJSON transformation

See the Vega geoJSON, geoPoint, geoshape and geopath documentation.

Generate a renderer instance that maps GeoJSON features to a shape instance for use with the shape mark. Similar to the trGeoPath, but rather than generate intermediate SVG path strings, this transform produces a shape instance that directly generates drawing commands during rendering resulting in improved performance when using canvas rendering for dynamic maps.

trGeoPath : String -> List GeoPathProperty -> Transform

Map GeoJSON features to SVG path strings according to a provided cartographic projection for use with the path mark. Similar to the trGeoShape but immediately generates SVG path strings.

Data field containing GeoJSON data when applying a geoShape or geoPath transformation. If unspecified, the full input data object will be used.

Default radius (in pixels) to use when drawing GeoJSON Point and MultiPoint geometries. An expression value may be used to set the point radius as a function of properties of the input GeoJSON.

gpAs : String -> GeoPathProperty

Output field in which to write a generated shape instance following a geoShape or geoPath transformation.

Consolidate geographic data into a single feature collection. This can be captured as a signal that will represent the consolidated feature collection.

Fields containing longitude (first parameter) and latitude (second parameter) to be consolidated into a feature collection by a geoJSON transform.

Field containing the GeoJSON objects to be consolidated into a feature collection by a geoJSON transform.

Name of the a new signal to capture the output of generated by a geoJSON transform.

trGeoPoint : String -> Field -> Field -> Transform

Project a longitude, latitude pair to (x,y) coordinates according to the given map projection. The first parameter is the name of the map projection to use, the second and third the fields containing the longitude and latitude values respectively. This version generates two new fields with the name x and y holding the projected coordinates.

trGeoPointAs : String -> Field -> Field -> String -> String -> Transform

Similar to trGeoPoint but allowing the projected coordinates to be named (last two parameters).

Graticule Generation

See the Vega graticule documentation.

Generate a reference grid of meridians (longitude) and parallels (latitude) for cartographic maps. The default graticule has meridians and parallels every 10° between ±80° latitude; for the polar regions meridians are every 90°.

It generates a new data stream containing a single GeoJSON data object for the graticule, which can subsequently be drawn using the geopath or geoshape transform.

Major and minor extents of a graticule to be the same values. Parameter should evaluate to a two-element list representing longitude and latitude extents.

Major extent of a graticule. Parameter should evaluate to a two-element list representing longitude and latitude extents.

Minor extent of a graticule. Parameter should evaluate to a two-element list representing longitude and latitude extents.

Major and minor step angles of a graticule to be the same values. Parameter should be a two-element list representing longitude and latitude spacing.

Major step angles of a graticule. Parameter should be a two-element list representing longitude and latitude spacing.

Minor step angles of a graticule. Parameter should be a two-element list representing longitude and latitude spacing.

Field used to bin when generating a graticule.

Precision in degrees with which graticule arcs are generated. The default value is 2.5 degrees.

Layout Transforms

See the Vega link path documentation.

Route a visual link between two nodes to draw edges in a tree or network layout. Writes one property to each datum, providing an SVG path string for the link path.

Field for the source x-coordinate in a linkPath transformation. The default is source.x.

Field for the source y-coordinate in a linkPath transformation. The default is source.y.

Field for the target x-coordinate in a linkPath transformation. The default is target.x.

Field for the target y-coordinate in a linkPath transformation. The default is target.y.

Orientation of a link path in a linkPath transformation. If a radial orientation is specified, x and y coordinate parameters will be interpreted as an angle (in radians) and radius, respectively.

Shape of a link path in a linkPath transformation.

Name for the output field of a link path in a linkPath transformation. If not specified, the default is "path".

Straight lines linking nodes in a link diagram.

Arcs of circles linking nodes in a link diagram.

Curved lines linking nodes in a link diagram.

Curved diagonal lines linking nodes in a link diagram.

Orthogonal lines linking nodes in a link diagram.

lsSignal : String -> LinkShape

Line shape between nodes referenced by the value in the named signal.

Angular Layouts

See the Vega pie documentation.

Calculates the angular extents of arc segments laid out in a circle, for example to create a pie chart. Writes two properties to each datum, indicating the starting and ending angles (in radians) of an arc.

The field to encode with angular spans in a pie chart transform.

The starting angle in radians in a pie chart transform. The default is 0 indicating that the first slice starts 'north'.

End angle in radians in a pie chart transform. The default is 2 PI indicating the final slice ends 'north'.

Indicate whether or not pie slices should be stored in angular size order.

piAs : String -> String -> PieProperty

Output fields for the computed start and end angles for each arc in a pie transform.

Stacked Layouts

See the Vega stack documentation.

Compute a layout by stacking groups of values. The most common use case is to create stacked graphs, including stacked bar charts and stream graphs. This transform writes two properties to each datum, indicating the starting and ending stack values.

Field that determines the stack heights in a stack transform.

Grouping of fields with which to partition data into separate stacks in a stack transform.

Criteria for sorting values in a stack transform.

Baseline offset used in a stack transform.

stAs : String -> String -> StackProperty

Names of the output fields for the computed start and end stack values of a stack transform.

Offset a stacked layout using a baseline at the foot of a stack.

Offset a stacked layout using a central stack baseline.

Rescale a stacked layout to use a common height while preserving relative size of stacked quantities.

stSignal : String -> StackOffset

Stacking offset referenced by the value in the named signal.

Force-Generated Layouts

See the Vega force documentation.

Compute a force-directed layout. This layout transformation uses a model in which data objects act as charged particles (or nodes), optionally connected by a set of edges (or links). A set of forces is used to drive a physics simulation that determines the node positions.

Whether a simulation in a force transformation should be computed in batch to produce a static layout (true) or should be animated (false).

Whether a simulation in a force transformation should restart when node object fields are modified.

Number of iterations in a force transformation when in static mode (default 300).

Energy level or “temperature” of a simulation under a force transform. Alpha values lie in the range [0, 1]. Internally, the simulation will decrease the alpha value over time, causing the magnitude of updates to diminish.

Minimum amount by which to lower the alpha value on each simulation iteration under a force transform.

Target alpha value to which a simulation converges under a force transformation.

Friction to be applied to a simulation in a force transformation. This is applied after the application of any forces during an iteration.

Forces to include in a force-directed simulation resulting from a force transform.

fsAs : String -> String -> String -> String -> ForceSimulationProperty

Names of the output fields to which node positions and velocities are written after a force transformation. The default is ["x", "y", "vx", "vy"] corresponding to the order of parameter names.

Force that pulls all nodes towards a shared centre point in a force simulation. The two parameters specify the x and y coordinates of the centre point.

Collision detection force that pushes apart nodes whose circular radii overlap in a force simulation. The first parameter specifies the radius of the node to which it applies. The second enables the strength and number of iterations to be specified.

n-body force that causes nodes to either attract or repel each other in a force simulation. The parameter enables the strength, theta value, and min/max distances over which the force acts to be specified.

Force attraction towards a particular x-coordinate (first parameter), with a given strength (second parameter) on a per-node basis.

Force attraction towards a particular y-coordinate (first parameter), with a given strength (second parameter) on a per-node basis.

Relative strength of a force or link constraint in a force simulation.

Distance in pixels by which the link constraint should separate nodes (default 30).

Number of iterations to run collision detection or link constraints (default 1) in a force directed simulation.

Approximation parameter for aggregating more distance forces in a force-directed simulation (default 0.9).

Minimum distance over which an n-body force acts. If two nodes are closer than this value, the exerted forces will be as if they are distanceMin apart (default 1).

Maximum distance over which an n-body force acts. If two nodes exceed this value, they will not exert forces on each other.

Data field for a node’s unique identifier. If provided, the source and target fields of each link should use these values to indicate nodes.

Voronoi Diagram

See the Vega Voronoi documentation.

Compute a voronoi diagram for a set of input points and return the computed cell paths.

Extent of the voronoi cells in a voronoi transform. The single parameter should evaluate to a list of two numbers representing the bottom-right of the extent. The top-left is assumed to be [0,0].

Extent of the voronoi cells in a voronoi transform. The two parameters should each evaluate to a list of two numbers representing the coordinates of the top-left and bottom-right of the extent respectively.

voAs : String -> VoronoiProperty

Name of the output field of a voronoi transform. If not specified, the default is path.

Word Cloud layout

See the Vega wordcloud documentation.

Compute a word cloud layour similar to a 'wordle'. Useful for visualising the relative frequency of words or phrases.

mark text
    [ mTransform
        [ trWordcloud
            [ wcSize (nums [ 800, 400 ])
            , wcText (field "text")
            , wcRotate (numExpr (exField "datum.angle"))
            , wcFontSize (numExpr (exField "datum.count"))
            , wcFontWeight (strExpr (exField "datum.weight"))
            , wcFontSizeRange (nums [ 12, 56 ])
            ]
        ]
    ]

Font family to use for a word in a wordcloud.

Font style to use for words in a wordcloud.

Font weights to use for words in a wordcloud.

Font size to use for a word in a wordcloud.

Font size range to use for words in a wordcloud. The parameter should resolve to a two-element list [min, max]. The size of words in a wordcloud will be scaled to lie in the given range according to the square root scale.

Padding, in pixels, to be placed around words in a wordcloud.

Angle in degrees of words in a wordcloud layout.

Data field with the input word text for a wordcloud transform.

Size of layout created by a wordcloud transform. The parameter should resolve to a two-element list [width, height] in pixels.

Spiral layout method for a wordcloud transform.

Archimedean spiraling for sequential positioning of words in a wordcloud.

Rectangular spiraling for sequential positioning of words in a wordcloud.

spSignal : String -> Spiral

Word cloud spiral type (archimedean or rectangular) referenced by the value in the named signal.

String
-> String
-> String
-> String
-> String
-> String
-> String

Name output fields created by a word cloud transform. The parameters map to the following default values: x, y, font, fontSize, fontStyle, fontWeight and angle.

Hierarchy Transforms

See the Vega nest, stratify, pack, partition, tree, tree links and treemap documentation.

trNest : List Field -> Boo -> Transform

Generate a tree data structure from input data objects by dividing children into groups based on distinct field values. This can provide input to tree layout methods such as trTree, trTreemap, trPack and trPartition.

Generate a hierarchical (tree) data structure from input data objects, based on key fields that match an id for each node (first parameter) and their parent's key (second parameter) nodes. Internally, this transform generates a set of tree node objects that can then be processed by tree layout methods such as tree, treemap, pack, and partition.

Compute an enclosure diagram that uses containment (nesting) to represent a hierarchy. The size of the leaf circles encodes a quantitative dimension of the data. The enclosing circles show the approximate cumulative size of each subtree, but due to wasted space there is some distortion; only the leaf nodes can be compared accurately.

The data field corresponding to a numeric value for the node in a packing transform. The sum of values for a node and all its descendants is available on the node object as the value property. If radius is null, this field determines the node size.

Packing transform sorting properties. The inputs to subject to sorting are tree node objects, not input data objects.

The size of a packing layout, provided as a two-element list in [width, height] order (or a signal that generates such a list).

Node radius to use in a packing transform. If Nothing (the default), the radius of each leaf circle is derived from the field value.

The approximate padding to include between packed circles.

paAs : String -> String -> String -> String -> String -> PackProperty

The names to give the output fields of a packing transform. The default is ["x", "y", "r", "depth", "children"], where x and y are the layout coordinates, r is the node radius, depth is the tree depth, and children is the count of a node’s children in the tree.

Compute the layout for an adjacency diagram: a space-filling variant of a node-link tree diagram. Nodes are drawn as solid areas (either arcs or rectangles) sized by some quantitative field, and their placement relative to other nodes reveals their position in the hierarchy.

Data field corresponding to a numeric value for a partition node. The sum of values for a node and all its descendants is available on the node object as the value property. This field determines the size of a node.

Sorting properties of sibling nodes during a partition layout transform.

Padding between adjacent nodes for a partition layout transform.

Whether or not node layout values should be rounded in a partition transform. The default is false.

Size of a partition layout as two-element list corresponding to [width, height] (or a signal that generates such a list).

String
-> String
-> String
-> String
-> String
-> String

Output field names for the output of a partition layout transform. The parameters correspond to the (default name) fields x0, y0, x1, y1, depth and children.

Compute a node-link diagram layout for hierarchical data. Supports both cluster layouts (for example to create dendrograms) and tidy layouts.

Data corresponding to a numeric value to be associated with nodes in a tree transform.

Sorting properties of sibling nodes in a tree layout transform.

Layout method used in a tree transform.

A clustering tree layout method to be used in a tree transform.

A tidy tree layout method to be used in a tree transform.

meSignal : String -> TreeMethod

Tree layout method (tidy or cluster) referenced by the value in the named signal.

Size of of a tree layout as a two-element [width,height] list (or a signal that generates such a list).

Size of each node in a tree layout as a two-element [width,height] list (or a signal that generates such a list).

teAs : String -> String -> String -> String -> TreeProperty

Output field names within which to write the results of a tree layout transform. The parameters represent the names to replace the defaults in the following order: x, y, depth and children.

Recursively subdivide an area into rectangles with areas proportional to each node’s associated value.

Field corresponding to a numeric value for a treemap node. The sum of values for a node and all its descendants is available on the node object as the value property. This field determines the size of a node.

Sorting properties of sibling nodes is in a treemap layout transform.

Layout method to use in a treemap transform.

A squarifying treemap layout method used in a treemap transform.

A resquarifying treemap layout method used in a treemap transform.

A binary treemap layout method used in a treemap transform.

A slicing treemap layout method used in a treemap transform.

A dicing treemap layout method used in a treemap transform.

A slice and dice treemap layout method used in a treemap transform.

Treemap layout method referenced by the value in the named signal.

Inner and outer padding values for a treemap layout transform.

Inner padding values for a treemap layout transform.

Outer padding values for a treemap layout transform.

Padding between the top edge of a node and its children in a treemap layout transform.

Padding between the left edge of a node and its children in a treemap layout transform.

Padding between the bottom edge of a node and its children in a treemap layout transform.

Padding between the right edge of a node and its children in a treemap layout transform.

Target aspect ratio for the Squarify or Resquarify treemap layout trqnsformations. The default is the golden ratio, φ = (1 + sqrt(5)) / 2.

Whether or not node layout values should be rounded in a treemap transform. The default is false.

Size of a treemap layout as two-element list (or signal) corresponding to [width, height].

tmAs : String -> String -> String -> String -> String -> String -> TreemapProperty

Output field names for the output of a treemap layout transform. The parameters correspond to the (default name) fields x0, y0, x1, y1, depth and children.

Signals, Triggers and Interaction Events

See the Vega signal documentation

Signals

signals : List Spec -> ( VProperty, Spec )

Create the signals used to add dynamism to the visualization.

si =
    signals
        << signal "chartSize" [ siValue (vNum 120) ]
        << signal "chartPad" [ siValue (vNum 15) ]
        << signal "chartStep" [ siUpdate "chartSize + chartPad" ]
        << signal "width" [ siUpdate "chartStep * 4" ]
signal : String -> List SignalProperty -> List Spec -> List Spec

Signal to be used to add a dynamic component to a visualization.

A unique name to be given to a signal. Signal names should be contain only alphanumeric characters (or “$”, or “_”) and may not start with a digit. Reserved keywords that may not be used as signal names are "datum", "event", "item", and "parent".

Initial value of a signal.

Bind a signal to an external input element such as a slider, selection list or radio button group.

Text description of a signal, useful for inline documentation.

Event stream handlers for updating a signal value in response to input events.

Update expression for a signal which may include other signals, in which case the signal will automatically update in response to upstream signal changes, so long as its react property is not false.

Whether a signal update expression should be automatically re-evaluated when any upstream signal dependencies update. If false, the update expression will only be run upon initialization.

Make signal updates target a signal in an enclosing scope. Used when creating nested signals in a group mark.

User Interface Inputs

See the Vega signal binding documentation.

A checkbox input element.

A free text input element.

A numeric input element.

A date selector input element.

A local data time selector input element.

A time selector input element.

A month selector input element.

A week selector input element.

A radio buttons input element.

A slider input element.

A drop-down list input element.

A telephone number input element.

A color selector input element.

Delay event handling until the given milliseconds have elapsed since the last event was fired. Helps to limit event broadcasting.

A CSS selector string indicating the parent element to which the input element should be added. This allows the option of the input element to be outside the visualization container, which could be used for linking separate visualizations.

Options to be selected from a Radio or Select input element.

inMin : Float -> InputProperty

Minimum value for a range slider input element.

inMax : Float -> InputProperty

Maximum value for a range slider input element.

Step value (increment between adjacent selectable values) for a range slider input element.

Place-holding text for input elements before any value has been entered.

Whether autocomplete should be turned on or off for input elements that support it.

Event Handling

See the Vega event handler documentation documentation.

Event handler. The first parameter is the stream(s) of events to respond to. The second, a list of handlers that respond to the event stream.

signal "tooltip"
    [ siValue (vObject [])
    , siOn
        [ evHandler [ esObject [ esMark Rect, esType MouseOver ] ] [ evUpdate "datum" ]
        , evHandler [ esObject [ esMark Rect, esType MouseOut ] ] [ evUpdate "" ]
        ]
    ]

Expression to be evaluated when an event occurs, the result of which becomes the new signal value.

Name of a mark property encoding set to re-evaluate for the mark that is the source of an input event. This is required if evUpdate is not specified.

Whether or not updates that do not change a signal value should propagate. e.g., if true and an input stream update sets the signal to its current value, downstream signals will be notified of an update.

Event Streams

See the Vega event stream documentation

Event stream for modelling user input. The parameter represents a stream object which provides a more self-explanatory and robust form of specification than using a selector string.

esSignal : String -> EventStream

Signal that triggers an event stream. Allows an update to be triggered whenever the given signal changes.

Merge a list of event streams into a single stream.

Event stream to be used as input into a derived event stream. Useful if several event streams have a common element:

si =
    let
        esStart =
            esMerge
                [ esObject [ esType MouseDown ]
                , esObject [ esType TouchStart ]
                ]


        esEnd =
            esObject [ esType TouchEnd ]
    in
    signals
        << signal "down"
            [ siValue vNull
            , siOn
                [ evHandler [ esEnd ] [ evUpdate "null" ]
                , evHandler [ esStart ] [ evUpdate "xy()" ]
                ]
            ]
        << signal "xCur"
            [ siValue vNull
            , siOn
                [ evHandler [ esObject [ esStream esStart, esType TouchEnd ] ]
                    [ evUpdate "slice(xDom)" ]
                ]
            ]

Compact representation of an event stream for modelling user input (alternative to esObject).

Source for an event selector.

Type of event stream for handling user interaction events.

Event stream filter that lets only events that occur between the two given event streams from being handled. Useful for capturing pointer dragging as it is a pointer movement event stream that occurs between MouseDown and MouseUp events.

<< signal "myDrag"
    [ siValue (vNums [ 200, 200 ])
    , siOn
        [ evHandler
            [esObject
                [ esBetween [ esMark Rect, esType MouseDown ] [ esSource ESView, esType MouseUp ]
                , esSource ESView
                , esType MouseMove
                ]
            ]
            [ evUpdate "xy()" ]
        ]
    ]

This is equivalent to the more compact, but more error-prone event stream selector:

esSelector (str "[rect:mousedown, view:mouseup] > view:mousemove")

Whether or not an event stream is consumed once it has been captured. If false, the event is made available for subsequent event handling.

esFilter : List String -> EventStreamProperty

Predicate expressions that must all evaluate to True for an event to be captured.

Prevent events of a certain type from being handled.

Allow events of a certain type to be handled.

Minimum time to wait between event occurrence and processing. If a new event arrives during a debouncing window, the timer will restart and only the new event will be captured.

Named mark to be the source for an event stream. The name given here must correspond to that provided via mName.

Mark type to be the source for an event stream.

Minimum time in milliseconds between captured events. New events that arrive within the throttling window will be ignored. For timer events, this determines the interval between timer ticks.

Event selector used to generate an event stream.

Event source from any mark. Equivalent to the * selector.

Limit event source to events from the main group in which a nested group sits.

Event source from the current Vega view component.

Event source from the browser window object.

esDom : String -> EventSource

DOM node to be the source for an event selector. Referenced with a standard CSS selector.

Event types

Click interaction event type.

Double click interaction event type.

Drag entry interaction event type.

Drag exit interaction event type.

Drag over interaction event type.

Key down interaction event type.

Key press interaction event type.

Key up interaction event type.

Mouse down interaction event type.

Mouse movement interaction event type.

Mouse exit interaction event type.

Mouse over interaction event type.

Mouse up interaction event type.

Mouse wheel interaction event type.

Touch end interaction event type.

Touch move interaction event type.

Touch start interaction event type.

Wheel interaction event type.

Fire an event at a regular interval determined by the number of milliseconds provided with esThrottle.

on : List Trigger -> DataTable -> DataTable

Add a list of triggers to the given data table.

trigger : String -> List TriggerProperty -> Trigger

Creates a trigger that may be applied to a data table or mark. The first parameter is the name of the trigger and the second a list of trigger actions.

Expression that evaluates to data objects to insert as triggers. Insert operations are only applicable to datasets, not marks.

Expression that evaluates to data objects to remove. Remove operations are only applicable to datasets, not marks.

Remove all data object triggers.

Expression that evaluates to data objects to toggle. Toggled objects are inserted or removed depending on whether they are already in the dataset. Applicable only to datasets, not marks.

tgModifyValues : String -> String -> TriggerProperty

Data or mark modification trigger. The first parameter is an expression that evaluates to data objects to modify and the second an expression that evaluates to an object of name-value pairs, indicating the field values that should be updated.

mark symbol
    [ mFrom [ srData (str "countries") ]
    , mOn
        [ trigger "myDragSignal"
            [ tgModifyValues "dragged" "{fx: x(), fy: y()}" ]
        ]

would set the fx and fy properties on mark items referenced by myDragSignal to the current mouse pointer position.

Specifying Scales

See the Vega scale documentation.

scales : List Spec -> ( VProperty, Spec )

Create the scales used to map data values to visual properties.

sc =
    scales
        << scale "xScale"
            [ scType ScLinear
            , scDomain (doData [ daDataset "myData", daField (field "x") ])
            , scRange RaWidth
            ]
        << scale "yScale"
            [ scType ScLinear
            , scDomain (doData [ daDataset "myData", daField (field "y") ])
            , scRange RaHeight
            ]
scale : String -> List ScaleProperty -> List Spec -> List Spec

Scale to be used to map data values to visual properties.

Reverse the order of a scale range.

Whether to round numeric output values to integers. Helpful for snapping to the pixel grid.

Whether output values should be clamped to when using a quantitative scale range (default false). If clamping is disabled and the scale is passed a value outside the domain, the scale may return a value outside the range through extrapolation. If clamping is enabled, the output value of the scale is always within the scale’s range.

Expand a scale domain to accommodate the specified number of pixels on each end of a quantitative scale range or the padding between bands in a band scale.

Extend the range of a scale domain so it starts and ends on 'nice' round values.

Whether or not a scale domain should include zero. The default is true for linear, sqrt and power scales and false for all others.

Exponent to be used in power scale.

Base of the logorithm used in a logarithmic scale.

Alignment of elements within each step of a band scale, as a fraction of the step size. Should be in the range [0,1].

Whether or not ordinal domains should be implicitly extended with new values. If false, a scale will return undefined for values not included in the domain; if true, new values will be appended to the domain and an updated range value will be returned.

Expand a scale domain to accommodate the specified number of pixels between inner bands in a band scale.

Expand a scale domain to accommodate the specified number of pixels outside the outer bands in a band scale.

Step size for band and point scales.

Enable nice scaling.

Disable nice scaling.

Nice time intervals that try to align with rounded milliseconds.

Nice time intervals that try to align with whole or rounded seconds.

Nice time intervals that try to align with whole or rounded minutes.

Nice time intervals that try to align with whole or rounded hours.

Nice time intervals that try to align with whole or rounded days.

Nice time intervals that try to align with whole or rounded weeks.

Nice time intervals that try to align with whole or rounded months.

Nice time intervals that try to align with whole or rounded years.

Desired number of tick marks in a 'nice' scaling.

'Nice' temporal interval values when scaling.

niSignal : String -> ScaleNice

'nice' number-scaling type referenced by the value in the named signal.

Scale Types

Type of a named scale.

A band scale.

A linear band scale.

An ordinal band scale.

A linear scale.

A log scale.

An ordinal scale.

A point scale.

A power scale.

A quantile scale.

A quantizing scale.

A threshold scale.

A sequential scale.

A square root scale.

A temporal scale.

A UTC temporal scale.

scCustom : String -> Scale

Custom named scale.

scSignal : String -> Scale

Scaling referenced by the value in the named signal.

Scale Domains

The extent scaling input data.

Domain of input data values for a scale.

Maximum value of a scale domain, overriding a scDomain setting. Only intended for scales with continuous domains.

Minimum value of a scale domain, overriding a scDomain setting. This is only used with scales having continuous domains.

Insert a single mid-point value into a two-element scale domain. The mid-point value must lie between the domain minimum and maximum values. Useful for setting a midpoint for diverging color scales. Only used with scales having continuous, piecewise domains.

List value that directly overrides the domain of a scale. Useful for supporting interactions such as panning or zooming a scale. The scale may be initially determined using a data-driven domain, then modified in response to user input.

scales
    << scale "xDetail"
        [ scType ScTime
        , scRange RaWidth
        , scDomain (doData [ daDataset "sp500", daField (field "date") ])
        , scDomainRaw (vSignal "detailDomain")
        ]

List of numeric values (Nums) representing a scale domain.

List of strings (Strs) representing a scale domain.

doSignal : String -> ScaleDomain

Scale domain referenced by the value in the named signal.

doSignals : List String -> ScaleDomain

Scale domains referenced by the values in the named signals.

Data reference object specifying field values in one or more datasets to define a scale domain.

Scale Ranges

The extent of scaled values after transformation.

Range of a scale representing the set of visual values.

Use default width range of scale output values.

Use default height range of scale output values.

Use default (discrete) symbol range of scale output values.

Use default category range of scale output values.

Use default diverging range of scale output values.

Use default ordinal range of scale output values.

Use default (continuous) ramp range of scale output values.

Use default heatmap range of scale output values.

raNums : List Float -> ScaleRange

Scale range as a list of numbers.

raStrs : List String -> ScaleRange

Scale range as a list of strings.

Scale range as a list of values.

raSignal : String -> ScaleRange

Default range scaling referenced by the value in the named signal.

Scale range as a list of color schemes. The first parameter is the name of the colour scheme to use, the second any customising properties.

Scale range as a data reference object. This is used for specifying ordinal scale ranges as a series of distinct field values.

scale "myScale"
    [ scType ScOrdinal
    , scDomain (doData [ daDataset "clusters", daField (field "id") ])
    , scRange (raData [ daDataset "clusters", daField (field "name") ])
    ]

Step size for a band scale range.

Custom range default scheme. Used when a new named default has been created as part of a config setting is required.

Color Scales

See the Vega Vega color scale and color scheme documentation.

Name a color scheme to use.

Number of colors to use in a color scheme.

Extent of the color range to use in sequential and diverging color schemes. The parameter should evaluate to a two-element list representing the min and max values of the extent. For example [0.2, 1] will rescale the color scheme such that color values in the range [0, 0.2] are excluded from the scheme.

Interpolation method for a quantitative scale.

Cube helix color interpolation using the given gamma value (anchored at 1).

A long path cube-helix color interpolation using the given gamma value (anchored at 1).

A hue-chroma-luminance color interpolation.

A long-path hue-chroma-luminance color interpolation.

A hue-saturation-lightness color interpolation.

A long-path hue-saturation-lightness color interpolation.

rgb : Float -> CInterpolate

RGB color interpolation. The parameter is a gamma value to control the brightness of the color trajectory.

An CIELab color interpolation.

Specifying Projections

See the Vega map projection documentation.

projections : List Spec -> ( VProperty, Spec )

Create the projections used to map geographic data onto a plane.

pr =
    projections
        << projection "myProj" [ prType Orthographic ]
        << projection "myProj2" [ prType Albers, prRotate (nums [ -20, 15 ]) ]
projection : String -> List ProjectionProperty -> List Spec -> List Spec

Map projection for transforming geo data onto a plane.

An Albers map projection.

An Albers USA map projection that combines continental USA with Alaska and Hawaii.

An azimuthal equal area map projection.

An azimuthal equidistant map projection.

A conformal conic map projection.

An equal area conic map projection.

An equidistant conic map projection.

An equirectangular (default) map projection that maps longitude to x and latitude to y.

A gnomonic map projection.

A Mercator map projection.

A natural earth map projection.

An orthographic map projection.

A stereographic map projection.

A transverse Mercator map projection.

Custom projection type. Additional custom projections from d3 can be defined via the Vega API and called from with this function where the parameter is the name of the D3 projection to use (e.g. customProjection (str "winkel3")).

prSignal : String -> Projection

Map projection referenced by the value in the named signal.

Convenience function for generating a value representing a given projection type. Useful when generating signals representing projection types.

Type of map projection to use in a projection transformation.

Map projection’s clipping circle radius to the specified angle in degrees. A value of zero indicates antimeridian cutting should be applied rather than small-circle clipping.

Map projection’s viewport clip extent to the specified bounds in pixels. The extent bounds should be specified as a list of four numbers in [x0, y0, x1, y1] order where x0 is the left-side of the viewport, y0 is the top, x1 is the right and y1 is the bottom.

Map projection’s scale factor. The default scale is projection-specific. It corresponds linearly to the distance between projected points; however, scale factor values are not equivalent across projections.

Translation offset to the specified two-element list [tx, ty]. If not specified as a two-element list, returns the current translation offset which defaults to [480, 250]. The translation offset determines the pixel coordinates of the projection’s centre. The default translation offset places (0°,0°) at the centre of a 960×500 area.

Map projection’s centre as a two-element list of longitude and latitude in degrees.

Map projection’s three-axis rotation angle. This should be a two- or three-element list of numbers [lambda, phi, gamma] specifying the rotation angles in degrees about each spherical axis.

Default radius (in pixels) to use when drawing projected GeoJSON Point and MultiPoint geometries. The default value is 4.5.

Threshold for the projection’s adaptive resampling in pixels. This corresponds to the Douglas–Peucker distance. If precision is not specified, the projection’s current resampling precision which defaults to √0.5 ≅ 0.70710 is used.

'Hammer' map projection's coefficient (defaults to 2).

'Satellite' map projection's distance value. Values are expressed as a proportion of the Earth's radius (defaults to 2).

'Bottomley' map projection's fraction parameter (defaults to 0.5).

Number of lobes in radial map projections such as the Berghaus Star.

Parallel used for map projections such as the Armadillo (defaults to 20 degrees N).

Radius for the 'Gingery' map projection. Defaults to 30 degrees.

'Hill' map projection's ratio allowing it to vary continuously between Maurer 73 (0) and Eckert IV projections (infinity). Defaults to 1.

Spacing for a Lagrange conformal map projection (defaults to 0.5).

Tilt angle for a Satellite map projection (defaults to 0 degrees).

GeoJSON data to which a projection should attempt to automatically fit by setting its translate and scale values.

ds =
    dataSource [ data "mapData" [ daUrl (str "myGeoJson.json") ] ]


pr =
    projections
        << projection "myProjection"
            [ prType Orthographic
            , prSize (numSignal "[width,height]")
            , prFit (feName "mapData")
            ]
feName : String -> Feature

Name of a geoJSON feature. Can be used with prFit to fit a map projection scaling and centre to a given geoJSON feature or feature collection.

pr =
    projections
        << projection "myProjection"
            [ prType Orthographic
            , prSize (numSignal "[width,height]")
            , prFit (feName "mapData")
            ]

geoJSON feature referenced by the value in the named signal. Can be used with prFit to fit a map projection scaling and centre to a given geoJSON feature or feature collection.

ds =
    dataSource
        [ data "myLongLatData" []
            |> transform
                [ trGeoJson
                    [ gjFields (field "longitude") (field "latitude")
                    , gjSignal "feature"
                    ]
                ]
        ]


pr =
    projections
        << projection "myProjection"
            [ prType Orthographic
            , prSize (numSignal "[width,height]")
            , prFit (featureSignal "feature")
            ]

Display region into which the projection should be automatically fit. Used in conjunction with prFit. The region bounds should be specified in [x0, y0, x1, y1] order where x0 is the left-side, y0 is the top, x1 is the right and y1 is the bottom.

Width and height of the display region into which the projection should be automatically fit. Used in conjunction with prFit this is equivalent to calling prExtent with the top-left position set to (0,0). The region size should be specified in [width, height] order (or a signal that generates such a list).

Specifying Axes

See the Vega axis documentation.

axes : List Spec -> ( VProperty, Spec )

Create the axes used to visualize spatial scale mappings.

ax =
    axes
        << axis "myXScale" SBottom [ axTitle (str "Population") ]
        << axis "myYScale" SLeft [ axTickCount (num 5) ]
axis : String -> Side -> List AxisProperty -> List Spec -> List Spec

Create an axis used to visualize a spatial scale mapping. The first parameter is the name of the scale backing this axis, the second the position of the axis relative to the data rectangle and the third a list of optional axis properties. For example,

axes
    << axis "xScale" SBottom [ axTitle "Population", axZIndex (num 1) ]

Interpolation fraction indicating where, for band scales, axis ticks should be positioned. A value of 0 places ticks at the left edge of their bands. A value of 0.5 places ticks in the middle of their bands.

Whether or not the domain (the axis baseline) should be included as part of an axis.

Color of an axis domain line.

Opacity of an axis domain line.

Width in pixels of an axis domain line.

Mark encodings for custom axis styling.

The format specifier pattern for axis labels. For numerical values, must be a legal d3-format specifier. For date-time values, must be a legal d3-time-format specifier.

Whether or not grid lines should be included as part of an axis.

Color of an axis's grid lines.

Opacity of an axis's grid lines.

Stroke dash of an axis's grid lines as a list of dash-gap lengths.

Name of the scale to use for including grid lines. By default grid lines are driven by the same scale as the ticks and labels.

Width of an axis's grid lines in pixel units.

Whether or not if labels should be included as part of an axis.

Indicate how or if labels should be hidden if they exceed the axis range. If the parameter is NumNull, no check for label size is made. A number specifies the permitted overflow in pixels that can be tolerated.

Horizontal alignment of axis tick labels.

Vertical alignment of axis tick labels.

Angle of text for an axis.

Color of an axis label.

Opacity of an axis label.

Font name of an axis label.

Font size of an axis label.

Font weight of an axis label. This can be a number (e.g. vNum 300) or text (e.g. vStr "bold").

Indicate how labels at the beginning or end of an axis should be aligned with the scale range. The parameter represents a pixel distance threshold. Labels with anchor coordinates within this threshold distance for an axis end-point will be flush-adjusted. If NumNull, no flush alignment will be applied.

Number of pixels by which to offset flush-adjusted labels.

Maximum length in pixels of axis tick labels.

Padding in pixels between labels and ticks.

Strategy to use for resolving overlap of axis labels.

The minimum extent in pixels that axis ticks and labels should use. This determines a minimum offset value for axis titles.

Maximum extent in pixels that axis ticks and labels should use.

Orthogonal offset in pixels by which to displace the axis from its position along the edge of the chart.

The anchor position of the axis in pixels. For x-axes with top or bottom orientation, this sets the axis group x coordinate. For y-axes with left or right orientation, this sets the axis group y coordinate.

Whether or not ticks should be included as part of an axis.

Desired number of ticks, for axes visualizing quantitative scales. The resulting number may be different so that values are “nice” (multiples of 2, 5, 10) and lie within the underlying scale’s range.

Tick interval for a temporal axis. The first parameter is the type of temporal interval to use and the second the number of steps of that interval between ticks. e.g. to specify a tick is requested at 3 month intervals (January, April, July, October):

ax =
    axes
        << axis "xScale" SBottom [ axTemporalTickCount Month (num 3) ]

If the second parameter is not a positive value, the number of ticks will be auto-generated for the given interval type.

Color of an axis's ticks.

Opacity of an axis's ticks.

Whether or not an extra axis tick should be added for the initial position of an axis. This is useful for styling axes for band scales such that ticks are placed on band boundaries rather in the middle of a band.

Offset in pixels of an axis's ticks, labels and gridlines.

Whether or not pixel position values for an axis's ticks should be rounded to the nearest integer.

Width in pixels of an axis's ticks.

Size in pixels of axis ticks.

A title for an axis.

Horizontal alignment of an axis's title.

Angle of an axis's title text.

Vertical alignment of an axis's title.

Color of an axis's title.

Opacity of an axis's title.

Font to be used for an axis's title.

Size of font in pixels for an axis's title.

Font weight of an axis's title. This can be a number (e.g. vNum 300) or text (e.g. vStr "bold").

Maximum allowed length of an axis's title.

Offset in pixels between an axis's labels and title.

X position of an axis title relative to the axis group, overriding the standard layout.

Y position of an axis title relative to the axis group, overriding the standard layout.

Explicitly set an axis tick and label values.

The z-index indicating the layering of an axis group relative to other axis, mark and legend groups. The default value is 0 and axes and grid lines are drawn behind any marks defined in the same specification level. Higher values (1) will cause axes and grid lines to be drawn on top of marks.

Reference the axis element when customising an axis.

Reference the tick element when customising an axis.

Reference the grid element when customising an axis.

Reference the label element when customising an axis.

Reference the title element when customising an axis.

Reference the domain (line) element when customising an axis.

Left side, used to specify an axis position.

Right side, used to specify an axis position.

Top side, used to specify an axis position.

Bottom side, used to specify an axis position.

siSignal : String -> Side

Rectangular side referenced by the value in the named signal.

No overlap strategy to be applied when there is not space to show all items on an axis.

Give all items equal weight in overlap strategy to be applied when there is not space to show them all on an axis.

Greedy overlap strategy to be applied when there is not space to show all items on an axis.

Overlap strategy referenced by the value in the named signal.

Specifying Legends

See the Vega legend documentation

legends : List Spec -> ( VProperty, Spec )

Create legends used to visualize color, size and shape mappings. Commonly the functional composition operator (<<) is used to combine multiple legend specifications. For example,

lg =
    legends
        << legend
            [ leTitle (str "Income")
            , leOrient BottomRight
            , leType LSymbol
            , leSize "mySizeScale"
            ]
        << legend
            [ leTitle (str "Nationality")
            , leOrient TopRight
            , leType LSymbol
            , leFill "myColorScale"
            ]
legend : List LegendProperty -> List Spec -> List Spec

Create a legend used to visualize a color, size or shape mapping.

Type of legend.

Direction of a legend.

Orientation of the legend, determining where the legend is placed relative to a chart’s data rectangle.

Name of the scale that maps to the legend symbols' fill colors.

Name of the scale that maps to the legend symbols' opacities.

Name of the scale that maps to the legend symbols' shapes.

Name of the scale that maps to the legend symbols' sizes.

Name of the scale that maps to the legend symbols' strokes.

Name of the scale that maps to the legend symbols' stroke dashing.

Mark encodings for custom legend styling. For example, to create a horizontal dash symbol (using a simple SVG path) for each legend item:

legend
    [ leEncode [ enSymbols [ enEnter [ maShape [ vStr "M-0.5,0H1" ] ] ] ]
    , leStroke "myColourScale"
    ]

Format pattern for legend labels. Text should be either a d3-format specifier or a d3-time-format specifier.

Alignment to apply to symbol legends rows and columns.

Height in pixels to clip a symbol legend entries and limit its size. By default no clipping is performed.

Number of columns in which to arrange symbol legend entries. A value of 0 or lower indicates a single row with one column per entry. The default is 0 for horizontal symbol legends and 1 for vertical symbol legends.

Horizontal padding between entries in a symbol legend.

Vertical padding between entries in a symbol legend.

Corner radius for an enclosing legend rectangle.

Bbackground color of an enclosing legend rectangle.

Offset in pixels by which to displace the legend from the data rectangle and axes.

Padding between the border and content of the legend group.

Border color of an enclosing legend rectangle.

Stroke width of the color of a legend's gradient border.

Opacity of a color gradient in a legend.

Maximum allowed length of gradient labels in a legend.

Vertical offset in pixels for gradient labels in a legend.

Length in pixels of the primary axis of a color gradient in a legend. This value corresponds to the height of a vertical gradient or the width of a horizontal gradient.

Thickness in pixels of the color gradient in a legend. This value corresponds to the width of a vertical gradient or the height of a horizontal gradient.

Color of a legend's color gradient border.

Width of a legend's color gradient border.

Horizontal text alignment for a legend label.

Vertical text alignment for a legend label.

Text color for legend labels.

Font for legend labels.

Font size in pixels for legend labels.

Font weight for legend labels.

Maximum allowed length in pixels of a legend label.

Opacity for a legend's labels.

Horizontal pixel offset for a legend's symbols.

Strategy to use for resolving overlap of labels in gradient legends.

Fill color for legend symbols.

Default fill color for legend symbols. This is only applied if there is no fill scale color encoding for the legend.

Default stroke color for legend symbols. This is only applied if there is no stroke scale color encoding for the legend.

Default direction for legend symbols.

Offset in pixels between legend labels their corresponding symbol or gradient.

Default symbol area size in square pixel units.

Border color for legend symbols.

Default symbol border width used in a legend.

Opacity for a legend's symbols.

Default symbol shape used in a legend.

Desired number of tick values for quantitative legends.

Ddesired number of ticks for a temporal legend. The first parameter is the type of temporal interval to use and the second the number of steps of that interval between ticks. For example to specify a tick is requested at six-month intervals (e.g. January, July):

lg =
    legends
        << legend
            [ leFill "cScale"
            , leType LGradient
            , leFormat (str "%b %Y")
            , leTemporalTickCount Month (num 6)
            ]

If the second parameter is not a positive value, the number of ticks will be auto-generated for the given interval type.

Title for the legend (none by default).

Horizontal alignment for a legend title.

Vertical alignment for a legend title.

Text color for a legend title.

Opacity for a legend's title.

Font for a legend title.

Font size in pixel units for a legend title.

Font weight for a legend title.

Maximum allowed length in pixels of a legend title.

Padding between the legend title and entries.

Explicitly set visible legend values.

z-index indicating the layering of the legend group relative to other axis, mark and legend groups. The default value is 0.

legend with discrete items.

Legend to represent continuous data.

ltSignal : String -> LegendType

Legend type (symbol or gradient) referenced by the value in the named signal.

Position legend to the left of the visualization it describes.

Position legend to the top-left of the visualization it describes.

Position legend at the top of the visualization it describes.

Position legend to the top-right of the visualization it describes.

Position legend to the right of the visualization it describes.

Position legend to the bottom-right of the visualization it describes.

Position legend at the bottom of the visualization it describes.

Position legend to the bottom-left of the visualization it describes.

Do not perform automatic legend positioning (allows legend to be located explicitly via x y coordinates).

Legend position referenced by the value in the named signal.

Custom encoding for a legend group mark.

Custom ecoding for a legend title.

Custom encoding for legend labels.

Custom encoding for symbol (discrete) legends.

Custom encoding for gradient (continuous) legends.

Name for a custom legend encoding set.

Whether or not a custom legend encoding set is to be interactive.

Specifying Titles

See the Vega title documentation

title : Str -> List TitleProperty -> ( VProperty, Spec )

Top-level title to be displayed as part of a visualization. The first paramter is the text of the title to display, the second any optional properties for customising the title's appearance.

Anchor positioning of a title. Used for aligning title text.

Angle in degrees of a title.

Anchor some text at its start.

Anchor some text in its start.

Anchor some text at its end.

anchorSignal : String -> Anchor

Indicate that an anchor position is to be determined by a named signal. The signal should generate one of start, middle or end.

Horizontal alignment of a title. If specified this will override the tiAnchor setting (useful when aligning rotated title text).

Vertical title text baseline.

Color of a title.

Mark encodings for custom title styling. This is a standard encoding for text marks and may contain enEnter, enUpdate, enExit and enHover specifications.

Font name of a title.

Font size of a title.

Font weight of a title (can be a number such as vnum 300 or text such as vStr "bold").

Reference frame for the anchor position of a title.

Title anchor position calculation assuming text anchor is relative to the full bounding box.

Title anchor position calculation assuming text anchor is relative to the group width / height.

tfSignal : String -> TitleFrame

Title anchor calcuation type (bounds or group) referenced by the value in the named signal.

Whether or not a title's properties should respond to input events such as mouse hover.

Maximim allowed length of a title in pixels.

tiName : String -> TitleProperty

Mark name to apply to a title text mark. This name can be used to refer to the title mark with an event stream definition.

Orthogonal offset in pixels by which to displace the title from its position along the edge of the chart.

Position a title relative to the chart.

Mark style property to apply to the title text mark. If not specified the default style of group-title is used.

z-index indicating the layering of the title group relative to other axis, mark and legend groups.

Specifying Layout

See the Vega layout documentation.

layout : List LayoutProperty -> ( VProperty, Spec )

Create a layout used in the visualization. For example the following creates a three-column layout with 20 pixel padding between columns:

lo =
    layout [ loColumns (num 3), loPadding (num 20) ]

Indicate grid elements will be aligned and each row or column will be sized identically based on the maximum observed size.

Indicate grid elements will be aligned into a clean grid structure, but each row or column may be of variable size.

Indicate a flow grid layout will be used in which adjacent plots are placed one after the other.

Layout alignment referenced by the value in the named signal.

Layout alignment to apply to grid rows. Used in cases when alignment rules are different for rows and columns.

Layout alignment to apply to grid columns. Used in cases when alignment rules are different for rows and columns.

Only the width and height values of a group mark are to determine the extent of a sub-plot in a grid layout. Useful when attempting to place sub-plots without axes or legends into a uniform grid structure.

Entire calculated bounds (including axes, title, and legend) to determine the extent of a sub-plot in a grid layout.

Indicate that the bounds calculation type is to be determined by a named signal.

Alignment to apply to grid rows and columns in a grid layout.

Bounds calculation method to use for determining the extent of a sub-plot in a grid layout.

Number of columns to include in a grid layout. If unspecified, a single row with unlimited columns will be assumed.

Padding in pixels to add between elements within rows and columns of a grid layout.

Similar to loPadding but allowing row and column settings to be specified separately.

Orthogonal offset in pixels by which to displace grid header, footer and title cells from their position along the edge of a grid layout.

Similar to loOffset but allowing row and column settings to be specified separately.

Band positioning in the interval [0,1] indicating where in a cell a header should be placed in a grid layout. For a column header, 0 maps to the left edge of the header cell and 1 to right edge. For a row footer, the range maps from top to bottom.

Similar to loFHeaderBand but allowing row and column settings to be specified separately.

Band positioning in the interval [0,1] indicating where in a cell a footer should be placed in a grid layout.

Similar to loFooterBand but allowing row and column settings to be specified separately.

Title placement in a grid layout. For a column title, 0 maps to the left edge of the title cell and 1 to right edge. The default value is 0.5, indicating a centred position.

Similar to loTitleBand but allowing row and column settings to be specified separately.

Specifying Marks

See the Vega mark documentation.

## Top-Level Marks

marks : List Spec -> ( VProperty, Spec )

Create the marks used in the visualization. Multiple mark specifications are commonly combined using the functional composition operator (<<). For example,

  mk =
      marks
          << mark line
              [ mFrom [ srData (str "myData") ]
              , mEncode
                  [ enEnter
                      [ maX [ vScale "xScale", vField (field "distance") ]
                      , maY [ vScale "yScale", vField (field "energy") ]
                      , maStroke [ black ]
                      ]
                  ]
              ]
          << mark symbol
              [ mFrom [ srData (str "myData") ]
              , mEncode
                  [ enEnter
                      [ maX [ vScale "xScale", vField (field "distance") ]
                      , maY [ vScale "yScale", vField (field "energy") ]
                      , maFill [ white ]
                      , maStroke [ black ]
                      ]
                  ]
              ]
mark : Mark -> List TopMarkProperty -> List Spec -> List Spec

A mark definition. Marks form the visible components of a visualization. Each mark specification can include a list of mark properties (second parameter) that customise the appearance of the mark and relate its appearance to data streams or signals.

An arc mark.

An area mark.

An image mark.

An group mark for assembling nested marks.

A line mark.

A path mark.

A rectangle mark.

A rule (single line) mark.

A shape mark.

A symbol mark.

A text mark.

A trail mark (line with variable width).

Indicate whether or how marks should be clipped to a specified shape. For a simple case of clipping to the retangular 'data rectangle':

mClip (clEnabled true)

To clip by some abritrary simple polygon use clPath either to specify an SVG path string explicitly in pixel coordinates, or more usefully for geographic coordinates use the output of trGeoPath:

ds =
    dataSource
        [ data "myClippingPoly"
            [ daUrl (str "myPolyFile.json")
            , daFormat [ topojsonFeature "idOfClippingPoly" ]
            ]
            |> transform [ trGeoPath "myProjection" [] ]
        ...


mk =
    marks
          << mark path
              [ mFrom [ srData (str "myMapSource") ]
              , mClip (clPath (strSignal "data('myClippingPoly')[0]['path']"))
              ...

Description of a mark, useful for inline comments.

The visual encoding rules for a mark.

Data source to be visualized by a mark. If not specified, a single element dataset containing an empty object is assumed. The source can either be a dataset to use or a faceting directive to subdivide a dataset across a set of group marks.

Whether a mark can serve as an input event source. If false, no mouse or touch events corresponding to the mark will be generated.

Field to use as a unique key for data binding. When a visualization’s data is updated, the key value will be used to match data elements to existing mark instances. Use a key field to enable object constancy for transitions over dynamic data.

Unique name to be given to a mark. This name can be used to refer to the mark in another mark or within an event stream definition. SVG renderers will add this name value as a CSS class name on the enclosing SVG group (g) element containing the mark instances.

mOn : List Trigger -> TopMarkProperty

Triggers for modifying a mark's properties in response to signal changes.

Fields and sort order for sorting mark items. The sort order will determine the default rendering order. This is defined over generated scenegraph items and sorting is performed after encodings are computed, allowing items to be sorted by size or position. To sort by underlying data properties in addition to mark item properties, append the prefix datum to a field name.

mSort [ ( field "datum.y", Ascend ) ]

Post-encoding transforms to be applied after any encode blocks, that operate directly on mark scenegraph items (not backing data objects). These can be useful for performing layout with transforms that can set x, y, width, height, etc. properties. Only data transforms that do not generate or filter data objects should be used.

mStyle : List String -> TopMarkProperty

Names of custom styles to apply to a mark. A style is a named collection of mark property defaults defined within the configuration. These properties will be applied to the mark’s enter encoding set, with later styles overriding earlier styles. Any properties explicitly defined within the mark’s encode block will override a style default.

mGroup : List ( VProperty, Spec ) -> TopMarkProperty

Assemble a group of top-level marks. Used to create nested groups of marks within a Group mark (including further nested group specifications) by suppyling the specification as a series of properties. For example,

marks
    << mark group
        [ mFrom [ srData (str "myData") ]
        , mGroup [ mkGroup1 [], mkGroup2 [] ]
        ]

z-index (draw order) of a mark. Marks with higher values are drawn 'on top' of marks with lower numbers. Useful when drawing node-link diagrams and the node symbol should sit on top of connected edge lines.

Whether or not clipping should be applied to a set of marks within a group mark.

Clipping path to be applied to a set of marks within a region. Should be a valid SVG path string.

Clip a spherical outline subject to a given map projection name. This is useful in conjunction with map projections that include content such as graticule lines outside the bounds of the globe.

Name of the source for a set of marks.

Faceting

Split up a data source between group mark items.

srFacet : Str -> String -> List Facet -> Source

Create a facet directive for a set of marks. The first parameter is the name of the source dataset from which the facet partitions are to be generated. The second is the name to be given to the generated facet source. Marks defined with the faceted group mark can reference this data source name to visualize the local data partition.

mark group
    [ mFrom [ srFacet (str "table") "facet" [ faGroupBy [ field "category" ] ] ]
    , mEncode [ enEnter [ maY [ vScale "yScale", vField (field "category") ] ] ]
    , mGroup [ nestedMk [] ]
    ]


nestedMk =
    marks
        << mark rect
            [ mName "bars"
            , mFrom [ srData (str "facet") ]
            , mEncode
                [ enEnter
                    [ maY [ vScale "pos", vField (field "position") ]
                    , maHeight [ vScale "pos", vBand (num 1) ]
                    , maX [ vScale "xScale", vField (field "value") ]
                    , maX2 [ vScale "xScale", vBand (num 0) ]
                    , maFill [ vScale "cScale", vField (field "position") ]
                    ]
                ]
            ]

For pre-faceted data, the name of the data field containing a list of data values to use as the local partition. This is required if using pre-faceted data.

For data-driven facets, specify a list of field names by which to partition the data. This is required if using pre-faceted data.

For data-driven facets, a list aggregate transform properties for the aggregate data values generated for each facet group item.

Lower-level Mark Properties

See the Vega mark encoding documentation.

The primary x-coordinate of a mark in pixels.

The secondary x-coordinate of a mark in pixels.

The centre x-coordinate of a mark in pixels. This is an alternative to maX or maX2, not an addition.

The width of a mark in pixels.

The primary y-coordinate of a mark in pixels.

The secondary y-coordinate of a mark in pixels.

The centre y-coordinate of a mark in pixels. This is an alternative to maY or maY2, not an addition.

Height of a mark in pixels.

The opacity of a mark in the range 0 to 1.

Fill color of a mark.

The fill opacity of a mark in the range 0 to 1.

Stroke color of a mark.

Convenience function for specifying a transparent setting for marks that can be colored (e.g. with maFill)

Convenience function for specifying a black color setting for marks that can be colored (e.g. with maStroke)

Convenience function for specifying a white color setting for marks that can be colored (e.g. with maStroke)

Stroke opacity of a mark in the range 0 to 1.

Stroke width of a mark in pixels.

Stroke cap ending style for a mark.To guarantee valid stroke cap names, use strokeCapValue.

Stroke dash style of a mark. The list should consist of alternating dash-gap lengths in pixels.

A mark's offset of the first stroke dash in pixels.

Stroke join method for a mark. To guarantee valid stroke join names, use strokeJoinValue.

Miter limit at which to bevel a line join for a mark.

Cursor to be displayed over a mark. To guarantee valid cursor type names, use cursorValue.

URL to load upon mouse click. If defined, the mark acts as a hyperlink.

The tooltip text to show upon mouse hover over a mark. This may be specified directly, via a field, a signal or any other text-generating value.

An integer z-index indicating the layering order of sibling mark items. The default value is 0. Higher values (1) will cause marks to be drawn on top of those with lower z-index values. Setting the z-index as an encoding property only affects ordering among sibling mark items; it will not change the layering relative to other mark definitions.

Horizontal alignment of a text or image mark. To guarantee valid alignment type names, use hCenter, hLeft etc. For example:

<< mark text
    [ mEncode
        [ enEnter [ maAlign [ hCenter ] ] ]
    ]

Vertical baseline of a text or image mark. To guarantee valid alignment type names, use vTop, vMiddle etc. For example:

<< mark text
    [ mEncode
        [ enEnter [ maBaseline [ vTop ] ] ]
    ]

Corner radius in pixels of an arc or rect mark.

Interpolation style of a linear mark. To guarantee valid interpolation type names, use markInterpolationValue.

The interpolation tension in the range 0 to 1 of a linear mark. Applies only to cardinal and catmull-rom interpolators.

Indicate if the current data point in a linear mark is defined. If false, the corresponding line/trail segment will be omitted, creating a “break”.

Area in pixels of the bounding box of point-based mark such as a symbol. Note that this value sets the area of the mark; the side lengths will increase with the square root of this value.

Start angle in radians clockwise from north for an arc mark.

End angle in radians clockwise from north for an arc mark.

The padding angle in radians clockwise from north for an arc mark.

The inner radius in pixel units of an arc mark.

The outer radius in pixel units of an arc mark.

The orientation of an area mark. With a vertical orientation, an area mark is defined by the x, y, and (y2 or height) properties; with a horizontal orientation, the y, x and (x2 or width) properties must be specified instead. To guarantee valid orientation type names, use orientationValue.

Indicate if the visible group content should be clipped to the group’s specified width and height.

The URL of an image file to be displayed as an image mark. This may be specified directly, via a field, a signal or any other text-generating value.

Whether or not image aspect ratio should be preserved in an image mark.

The SVG path string describing the geometry of a path mark.

A shape instance that provides a drawing method to invoke within the renderer. Shape instances cannot be specified directly, instead they must be generated by a data transform such as symbol generation or a geoshape:

shapeEncoding =
    [ maShape [ symbolValue SymSquare ]
    , maStroke [ black ]
    ]


lg =
    legends
        << legend
            [ leFill "cScale"
            , leOrient BottomRight
            , leEncode [ enSymbols [ enUpdate shapeEncoding ] ]
            ]

A symbol shape that describes a symbol mark. For preset shapes, use symbolValue. For correct sizing of custom shape paths, define coordinates within a square ranging from -1 to 1 along both the x and y dimensions.

Rotation angle of the text in degrees in a text mark.

Direction text is rendered in a text mark. This determines which side is truncated in response to the text size exceeding the value of the limit parameter. To guarantee valid direction type names, use textDirectionValue.

Horizontal offset in pixels (before rotation), between the text and anchor point of a text mark.

Vertical offset in pixels (before rotation), between the text and anchor point of a text mark.

Ellipsis string for text truncated in response to the limit parameter of a text mark.

Typeface used by a text mark. This can be a generic font description such as sans-serif, monospace or any specific font name made accessible via a css font definition.

The font size in pixels used by a text mark.

The font weight, such as normal or bold used by a text mark.

The font style, such as normal or italic used by a text mark.

The maximum length of a text mark in pixels (default 0, indicating no limit). The text value will be automatically truncated if the rendered size exceeds this limit.

Polar coordinate radial offset in pixels, relative to the origin determined by the x and y properties of a text mark.

The text to display in a text mark.

Polar coordinate angle in radians, relative to the origin determined by the x and y properties of a text mark.

maCustom : String -> List Value -> MarkProperty

Create a custom mark property. For example:

mEncode
    [ enEnter
        [ maFill [ vScale "cScale", vField (field "group") ]
        , maCustom "myName" [ vScale "xScale", vField (field "group") ]
        ]
    ]

See the Vega Beeswarm plot example.

Properties to be encoded when a mark item is first instantiated or resized.

Properties to be encoded when a mark item is updated such as in response to a signal change.

Properties to be encoded when a pointer hovers over a mark item.

Properties to be encoded when the data backing a mark item is removed.

Named custom encoding set. Also requires a signal event handler with an encode directive.

Cubic basis spline interpolation between points.

Bundle curve interpolation between points.

Cubic cardinal spline interpolation between points.

Cubic Catmull-Rom spline interpolation between points.

Linear (straight) interpolation between points.

Cubic spline interpolation that preserves monotonicity between points.

Natural cubic spline interpolation between points.

Piecewise (stepped) constant interpolation function centred on each point in a squence.

Piecewise (stepped) constant interpolation function after each point in a squence.

Piecewise (stepped) constant interpolation function before each point in a squence.

A convenience function for generating a value representing a given mark interpolation type. Used instead of specifying an interpolation type as a literal string to avoid problems of mistyping the interpolation name.

signals
    << signal "interp" [ siValue (markInterpolationValue miLinear) ]

Specify a horizontal orientation of a mark, legend or link path (e.g. horizontally or vertically oriented bars).

Specify a vertical orientation of a mark, legend or link path (e.g. horizontally or vertically oriented bars).

Specify a radial orientation of a mark or link path. Note that not all marks can use a radial orientation.

orSignal : String -> Orientation

Orientation referenced by the value in the named signal.

A convenience function for generating a value representing a given mark orientation type. Used instead of specifying an orientation type as a literal string to avoid problems of mistyping its name.

 maOrient [ orientationValue Horizontal ]

Left horizontal text alignment.

Center horizontal text alignment.

Right horizontal text alignment.

haSignal : String -> HAlign

Horizontal text alignment referenced by the value in the named signal.

Convenience function for indicating a left horizontal alignment.

Convenience function for indicating a central horizontal alignment.

Convenience function for indicating a right horizontal alignment.

Top vertical text alignment.

Middle vertical text alignment.

Bottom vertical text alignment.

'Alphabetic' vertical alignment aligning font baseline. Applies to text marks only.

vaSignal : String -> VAlign

Vertical text alignment referenced by the value in the named signal.

Convenience function for indicating a top vertical alignment.

Convenience function for indicating a middle vertical alignment.

Convenience function for indicating a bottom vertical alignment.

Convenience function for indicating an alphabetic vertical alignment.

Specify a circular symbol for a shape mark.

Specify a cross symbol for a shape mark.

Specify a diamond symbol for a shape mark.

Specify a square symbol for a shape mark.

Specify an upward trianglular symbol for a shape mark.

Specify a downward trianglular symbol for a shape mark.

Specify a left-pointing trianglular symbol for a shape mark.

Specify a right-pointing trianglular symbol for a shape mark.

symPath : String -> Symbol

A custom symbol shape as an SVG path description.

symSignal : String -> Symbol

Symbol type referenced by the value in the named signal.

Convenience function for generating a value representing a given symbol type.

Butt stroke cap.

Square stroke cap.

Rounded stroke cap.

caSignal : String -> StrokeCap

Stroke cap (butt, round and square) referenced by the value in the named signal.

Convenience function for generating a value representing a given stroke cap type.

Mitered stroke join.

Bevelled stroke join.

Rounded stroke join.

joSignal : String -> StrokeJoin

Stroke join (miter, round or bevel) referenced by the value in the named signal.

Convenience function for generating a text string representing a given stroke join type. Used instead of specifying an stroke join type as a literal string to avoid problems of mistyping its name.

Left-to-right text render direction determining which end of a text string is truncated if it cannot be displayed within a restricted space.

Right-to-left text render direction determining which end of a text string is truncated if it cannot be displayed within a restricted space.

Text direction (ltr or rtl) referenced by the value in the named signal.

Create a text direction value.

Automatically determine a cursor type depending on interaction context.

Default cursor.

No cursor.

Context menu cursor.

Help cursor.

Pointer cursor.

Progress cursor.

Waiting cursor.

Cell cursor.

Crosshair cursor.

Text cursor.

Vertical text cursor.

Alias cursor.

Copy cursor.

Move cursor.

'No drop' cursor.

'Not allowed' cursor.

Scrolling cursor.

Resizing cursor.

Resizing cursor.

Resizing cursor.

Resizing cursor.

Resizing cursor.

Resizing cursor.

Resizing cursor.

Resizing cursor.

Resizing cursor.

Resizing cursor.

Resizing cursor.

Resizing cursor.

Resizing cursor.

Resizing cursor.

Zooming cursor.

Zooming cursor.

Grab cursor.

Grabbing cursor.

A convenience function for generating a text value representing a given cursor type.

Configuring Visualization Appearance

See the Vega configuration documentation.

config : List ConfigProperty -> ( VProperty, Spec )

Create a collection of configuration settings. This allows default stylings to be defined for a collection of visualizations or visualization components.

cf =
    config
        [ cfMark Text [ maFont [ vStr "Roboto Condensed, sans-serif" ] ]
        , cfTitle
            [ tiFont (str "Roboto Condensed, sans-serif")
            , tiFontWeight (vNum 500)
            , tiFontSize (num 17)
            ]
        , cfAxis AxAll
            [ axLabelFont (str "Roboto Condensed, sans-serif")
            , axLabelFontSize (num 12)
            ]
        ]

View Configuration

Default autosizing properties of view.

Default background of the view.

Default properties of the top-level group mark representing the data rectangle of a chart.

Event Configuration

Default filtering of events. This can specified in the first parameter as either a 'whitelist' (Allow) or 'blacklist' (Prevent) comprised the event types to be considered in the second parameter. If that list is empty, all event types will be placed in the black/white list.

Mark Configuration

Default properties of a given mark type.

Default properties of all marks.

Style Configuration

cfStyle : String -> List MarkProperty -> ConfigProperty

Create a named style. The first parameter is the name to give the style, the second its mark properties.

Axis Configuration

Default properties of axes.

All axis types to be configured with cfAxis.

Left axes to be configured with cfAxis.

Top axes to be configured with cfAxis.

Right axes to be configured with cfAxis.

Bottom axes to be configured with cfAxis.

x-axes to be configured with cfAxis.

y-axes to be configured with cfAxis.

Band axes to be configured with cfAxis.

Legend Configuration

Default properties of legends.

Title Configuration

Default properties of a title.

Scale Range Configuration

Create a named range to be used as part of a scale specification. The first parameter is the named range label (e.g. RaOrdinal, RaCategory, etc.). The second is the new range of values to be associated with this range.

cf =
    config [ cfScaleRange RaHeatmap (raScheme (str "greenblue") []) ]

Supplementary Properties

See the Vega specification documentation

autosize : List Autosize -> ( VProperty, Spec )

Indicate how the view is sized.

Interpret visualization dimensions to be for the data rectangle (external padding added to this size).

Interpret visualization dimensions to be for the entire visualization (data rectangle is shrunk to accommodate external decorations padding).

Interpret visualization width to be for the entire visualization (data rectangle is shrunk to accommodate external decorations and padding).

Interpret visualization height to be for the entire visualization (data rectangle is shrunk to accommodate external padding).

No autosizing to be applied.

Automatically expand size of visulization from the given dimensions in order to fit in all supplemtary decorations (legends etc.).

Interpret visualization width to be for the entire visualization (data rectangle is shrunk to accommodate external padding).

Recalculate autosizing on every view update.

asSignal : String -> Autosize

Indicate that an auto-sizing rule is to be determined by a named signal.

height : Float -> ( VProperty, Spec )

Override the default height of the visualization. If not specified the height will be calculated based on the content of the visualization.

padding : Float -> ( VProperty, Spec )

Padding around the visualization in pixel units. The way padding is interpreted will depend on the autosize properties.

paddings : Float -> Float -> Float -> Float -> ( VProperty, Spec )

Padding around the visualization in pixel units in left, top, right, bottom order.

width : Float -> ( VProperty, Spec )

Override the default width of the visualization. If not specified the width will be calculated based on the content of the visualization.

background : Str -> ( VProperty, Spec )

The fill background color of a visualization. This should be specified as a color string.

encode : List EncodingProperty -> ( VProperty, Spec )

Encoding directives for the visual properties of the top-level group mark representing a chart’s data rectangle. For example, this can be used to set a background fill color for the plotting area, rather than the entire view.


Type Reference

Types that are not specified directly, provided here for reference with links to the functions that generate them.

type Anchor

Generated by anStart, anMiddle, anEnd and anchorSignal.

Generated by axAll, axLeft, axTop, axRight, axBottom, axX, axY and axBand

type Boo

Generated by true, false, boos, booSignal, booSignals and booExpr

Generated by bcFull, bcFlush and bc.

type Case

Generated by lowercase, uppercase and mixedcase.

type Clip

Generated by clEnabled, clPath and clSphere.

Generated by cRGB, cHSL, cLAB and cHCL.

Generated by crFilter and crAs.

type Cursor

Generated by functions that start with cu.

type alias Data =
( VProperty, Spec )

Convenience type annotation label for use with data generation functions. Generated by dataSource but is also useful when creating your own data generating functions. For example:

myData : Int -> Data
myData yr =
    dataSource
        [ data "population" [ daSource "pop" ]
            |> transform [ trFilter (expr ("datum.year == " ++ toString yr)) ]
        ]
type alias DataColumn =
List LabelledSpec

A single column of data. Generated when creating inline data with dataColumn.

type alias DataRow =
Spec

A single row of data. Generated when creating inline data with dataRow.

type alias DataTable =
List LabelledSpec

A single table of data (collection of dataColumn specifications). Generated by data, dataFromColumns, dataFromRows, on and transform.

Generated by foNum, foBoo, foDate and foUtc.

Generated by dnPdf, dnCdf and dnSignal

Generated by dnExtent, dnMethod, dnSteps and dnAs.

Generated by efPrevent and efAllow.

Generated by esAll, esView, esScope, esWindow and esDom.

type Expr

Generated by exField and expr.

type Facet

Generated by faAggregate, faField and faGroupBy.

type Feature

Generated by featureSignal and feName.

type Field

Generated by fExpr, fDatum, fGroup, field, fParent and fSignal.

type Force

Generated by foCollide, foLink, foNBody, foX and foY.

Generated by gpField, gpAs and gpPointRadius.

type HAlign

Generated by haLeft, haCenter, haRight and haSignal.

Generated by , imMethod, imGroupBy and imValue.

Generated by ltSymbol, ltGradient and ltSignal.

Generated by luValues, luAs and luDefault.

type Mark

Generated by arc, area, image, group, line, path, rect, rule, shape, symbol, text and trail.

type Order

Generated by ascend, descend and orderSignal.

Generated by piGroupBy, piLimit and piOp.

Generated by doNums, doStrs and doData.

type Side

Generated by siLeft, siRight, siTop, siBottom and siSignal.

type Source

Generated by srData and srFacet.

type alias Spec =
Value

A Vega specification. Specs can be (and usually are) nested. They can range from a single Boolean value up to the entire Vega specification.

type Str

Generated by caButt, caRound, caSquare and caSignal.

Generated by joMiter, joRound, joBevel and joSignal

Generated by tfBounds, tfGroup and tfSignal.

Generated by meTidy, meCluster and meSignal.

type alias Trigger =
Spec

Generated by trigger.

Generated by voExtent, voSize and voAs.