gicentre/elm-vegalite/1.11.0

NOTE: the latest version is 5.8.0

VegaLite

Create Vega-Lite specifications in Elm. A specification can be sent to a Vega-Lite runtime to generate the graphics. While this is a pure Elm package, to generate the graphical output you probably want to send the JSON generated by toVegaLite via a port to some JavaScript that invokes the Vega-Lite runtime. Alternatively, to avoid coding the link to the Vega-Lite runtime, you can embed specifications directly in a litvis document.

Creating A Vega-Lite Specification

toVegaLite : List ( VLProperty, Spec ) -> Spec

Convert a list of Vega-Lite specifications into a single JSON object that may be passed to Vega-Lite for graphics generation. Commonly these will include at least data, mark and encoding specifications.

While simple functions like bar may be provided directly, it is usually clearer to label more complex ones such as encodings as separate expressions.

Specifications can be built up by chaining functions such as dataColumn or position. Functional composition using the << operator allows this to be done compactly.

let
    data =
        dataFromColumns []
            << dataColumn "a" (strs [ "C", "C", "D", "E" ])
            << dataColumn "b" (nums [ 2, 7, 1, 2 ])


    enc =
        encoding
            << position X [ pName "a", pMType Nominal ]
            << position Y [ pName "b", pMType Quantitative, pAggregate opMean ]
in
toVegaLite [ data [], bar [], enc [] ]

Top-level Vega-Lite properties. These are the ones that define the core of the visualization grammar. All VLProperties are created by functions in seven broad groups.

Data properties relate to the input data to be visualized. Generated by dataFromColumns, dataFromRows, dataFromUrl, dataFromSource, dataFromJson, dataSequence, sphere and graticule.

Transform properties indicate that some transformation of input data should be applied before encoding them visually. Generated by transform and projection they can include data transformations such as filter, binAs and calculateAs and geo transformations of longitude, latitude coordinates used by marks such as those generated by geoshape, point and line.

Mark functions specify the symbols used to visualize data items. Generated by functions such as circle, bar and line.

Encoding properties specify which data elements are mapped to which mark characteristics (known as channels). Generated by encoding they include encodings such as position, color, size, shape, text and hyperlink.

Composition properties allow visualization views to be combined to form more complex visualizations. Generated by layer, repeatFlow, repeat, facetFlow, facet, concat, columns, hConcat, vConcat, spec and resolve.

Interaction properties allow clicking, dragging and other interactions generated via a GUI or data stream to influence the visualization. Generated by selection.

Supplementary and configuration properties provide a means to add metadata and styling to one or more visualizations. Generated by name, title, description, background, width, height, padding, autosize, viewBackground, and configure.

type alias Spec =
Value

Part or all of a Vega-Lite specification. Specs are usually nested and can range from a single Boolean value up to the entire Vega-Lite specification.

type alias LabelledSpec =
( String, Spec )

A named Vega-Lite specification, usually generated by an elm-vega function. You shouldn't need to create LabelledSpec tuples directly, but are useful for type annotations.

combineSpecs : List LabelledSpec -> Spec

Combines a list of labelled specifications that may be passed to JavaScript for rendering. Useful when you wish to create a single page with multiple visualizations.

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

Creating the Data Specification

Functions and types for declaring the data to the visualized. See the Vega-Lite documentation.

dataFromUrl : String -> List Format -> Data

Declare a data source from a url. The URL can be a local path on a web server or an external (CORS) URL. A list of field formatting instructions can be provided as the second parameter or an empty list to use the default formatting.

dataFromColumns : List Format -> List DataColumn -> Data

Declare a data source from a list of column values. Each column should contain values of the same type, but columns each with a different type are permitted. If columns do not contain the same number of items the dataset will be truncated to the length of the shortest. A list of field formatting instructions can be provided as the first parameter or an empty list to use the default formatting. The columns are most easily generated with dataColumn:

data =
    dataFromColumns [ parse [ ( "Year", foDate "%Y" ) ] ]
        << dataColumn "Animal" (strs [ "Fish", "Dog", "Cat" ])
        << dataColumn "Age" (nums [ 28, 12, 6 ])
        << dataColumn "Year" (strs [ "2010", "2014", "2015" ])

For more complex inline data tables, such as mixtures of arrays and objects, consider using dataFromJson.

dataFromRows : List Format -> List DataRow -> Data

Declare a data source from a list of row values. Each row should contain a list of tuples in the form (column name, value). Each column can have a value of a different type but you must ensure that values are of the same type as others in the same column. A list of field formatting instructions can be provided as the first parameter or an empty list to use the default formatting. Rows are most easily generated with dataRow.

data =
    dataFromRows [ parse [ ( "Year", foDate "%Y" ) ] ]
        << dataRow [ ( "Animal", str "Fish" ), ( "Age", num 28 ), ( "Year", str "2010" ) ]
        << dataRow [ ( "Animal", str "Dog" ), ( "Age", num 12 ), ( "Year", str "2014" ) ]
        << dataRow [ ( "Animal", str "Cat" ), ( "Age", num 6 ), ( "Year", str "2015" ) ]

Generally, adding data by column is more efficient and less error-prone. For more complex inline data tables, such as mixtures of arrays and objects, consider using dataFromJson.

dataFromJson : Spec -> List Format -> Data

Declare a data source from a json specification. The most likely use-case is creating geojson objects with geometry, geometryCollection and geoFeatureCollection. For more general cases of json creation such as data tables that mix arrays and objects, consider Json.Encode.

let
    geojson =
        geometry (geoPolygon [ [ ( -3, 59 ), ( 4, 59 ), ( 4, 52 ), ( -3, 59 ) ] ]) []
in
toVegaLite
    [ width 200
    , height 200
    , dataFromJson geojson []
    , projection [ prType orthographic ]
    , geoshape []
    ]
dataFromSource : String -> List Format -> Data

Declare data from a named source. The source may be from named datasets within a specification or one created via the Vega View API. A list of field formatting instructions can be provided as the second parameter or an empty list to use the default formatting.

data = ...
json = ...
enc = ...
toVegaLite
    [ datasets [ ( "myData", data [] ),  ( "myJson", dataFromJson json [] ) ]
    , dataFromSource "myData" []
    , bar []
    , enc []
    ]
dataName : String -> Data -> Data

Name to give a data source. Useful when a specification needs to reference a data source, such as one generated via an API call.

data =
    dataFromUrl "myData.json" [] |> dataName "myName"
datasets : List ( String, Data ) -> Data

Create a dataset comprising a collection of named Data items. Each data item can be created with normal data generating functions such as dataFromRows or dataFromJson. These can be later referred to using dataFromSource.

import Json.Encode as JE


let
    data =
        dataFromRows []
            << dataRow [ ( "cat", str "a" ), ( "val", num 10 ) ]
            << dataRow [ ( "cat", str "b" ), ( "val", num 18 ) ]
    json =
        JE.list JE.object
            [ [ ( "cat", JE.string "a" ), ( "val", JE.float 120 ) ]
            , [ ( "cat", JE.string "b" ), ( "val", JE.float 180 ) ]
            ]


    enc = ...


in
toVegaLite
    [ datasets [ ( "myData", data [] ),  ( "myJson", dataFromJson json [] ) ]
    , dataFromSource "myData" []
    , bar []
    , enc []
    ]
dataColumn : String -> DataValues -> List DataColumn -> List DataColumn

Create a column of data. A column has a name and a list of values.

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

Create a row of data. A row comprises a list of (columnName, value) pairs.

type alias Data =
( VLProperty, Spec )

Convenience type annotation label for use with data generation functions.

myRegion : List DataColumn -> Data
myRegion =
    dataFromColumns []
        << dataColumn "easting" (nums [ -3, 4, 4, -3, -3 ])
        << dataColumn "northing" (nums [ 52, 52, 45, 45, 52 ])
type alias DataColumn =
List LabelledSpec

A single column of data. Used when generating inline data with dataColumn.

type alias DataRow =
Spec

A single row of data. Used when generating inline data with dataRow.

Geographic Data

geometry : Geometry -> List ( String, DataValue ) -> Spec

Geometric object to be used in a geoshape. The first parameter is the geometric type, the second an optional list of properties to be associated with the object.

  geojson =
      geometry (geoPolygon [ [ ( -3, 59 ), ( 4, 59 ), ( 4, 52 ), ( -3, 59 ) ] ]) []
geoFeatureCollection : List Spec -> Spec

Geo features to be used in a geoshape specification. Each feature object in this collection can be created with geometry.

geojson =
    geoFeatureCollection
        [ geometry (geoPolygon [ [ ( -3, 59 ), ( -3, 52 ), ( 4, 52 ), ( -3, 59 ) ] ])
            [ ( "myRegionName", str "Northern region" ) ]
        , geometry (geoPolygon [ [ ( -3, 52 ), ( 4, 52 ), ( 4, 45 ), ( -3, 52 ) ] ])
            [ ( "myRegionName", str "Southern region" ) ]
        ]
geometryCollection : List Spec -> Spec

Geometry objects to be used in a geoshape specification. Each geometry object can be created with geometry.

geojson =
    geometryCollection
        [ geometry (geoPolygon [ [ ( -3, 59 ), ( 4, 59 ), ( 4, 52 ), ( -3, 59 ) ] ]) []
        , geometry (geoPoint -3.5 55.5) []
        ]
geoPoint : Float -> Float -> Geometry

Point geometry for programmatically creating GeoShapes. Equivalent to the GeoJson geometry point type.

geoPoints : List ( Float, Float ) -> Geometry

Multi-point geometry for programmatically creating GeoShapes. Equivalent to the GeoJson geometry multi-point type.

geoLine : List ( Float, Float ) -> Geometry

Line geometry for programmatically creating GeoShapes. Equivalent to the GeoJson geometry line type.

geoLines : List (List ( Float, Float )) -> Geometry

Multi-line geometry for programmatically creating GeoShapes. Equivalent to the GeoJson geometry multi-line type.

geoPolygon : List (List ( Float, Float )) -> Geometry

Polygon geometry for programmatically creating GeoShapes. Equivalent to the GeoJson geometry polygon type.

geoPolygons : List (List (List ( Float, Float ))) -> Geometry

Multi-polygon geometry for programmatically creating GeoShapes. Equivalent to the GeoJson geometry multi-polygon type.

Data Generators

Functions that create new data sources.

dataSequence : Float -> Float -> Float -> Data

Generate a sequence of numbers as a data source between the value of the first parameter (inclusive) and the second (exclusive) in steps of the value of the third. The resulting sequence will have the name data. To give it an alternative name use dataSequenceAs

dataSequenceAs : Float -> Float -> Float -> String -> Data

Generate a sequence of numbers as a data source between the value of the first parameter (inclusive) and the second (exclusive) in steps of the value of the third. The resulting sequence will have the name provided as the fourth parameter.

sphere : Data

Generate a data source that is a sphere for bounding global geographic data. The sphere will be subject to whatever projection is specified for the view.

toVegaLite
    [ sphere
    , projection [ prType orthographic ]
    , geoshape [ maFill "aliceblue" ]
    ]

Generate a grid of lines of longitude (meridians) and latitude (parallels). The parameter can be used to specify the number and extent of lines, or to use default values, provide an empty list.

let
    proj =
        projection [ prType orthographic ]


    sphereSpec =
        asSpec [ sphere, geoshape [ maFill "aliceblue" ] ]


    gratSpec =
        asSpec
            [ graticule [ grStep ( 5, 5 ) ]
            , geoshape [ maFilled False, maStrokeWidth 0.3 ]
            ]
in
toVegaLite [ proj, layer [ sphereSpec, gratSpec ] ]
grStep : ( Float, Float ) -> GraticuleProperty

Set the step sizes between all graticule lines. The parameter is a (longitude,latitude) pair defining the EW and NS graticule intervals respectively.

grStepMajor : ( Float, Float ) -> GraticuleProperty

Set the step sizes between major graticule lines. By default, major graticule lines extend to both poles, but minor lines stop at ±80 degrees latitude. The parameter is a (longitude,latitude) pair defining the EW and NS graticule intervals respectively.

grStepMinor : ( Float, Float ) -> GraticuleProperty

Set the step sizes between minor graticule lines. By default, major graticule lines extend to both poles, but minor lines stop at ±80 degrees latitude. The parameter is a (longitude,latitude) pair defining the EW and NS graticule intervals respectively.

grExtent : ( Float, Float ) -> ( Float, Float ) -> GraticuleProperty

Set the extent of both major and minor graticule lines. The first parameter is a (longitude,latitude) pair defining the minimum extent, the second parameter the maximum extent.

grExtentMajor : ( Float, Float ) -> ( Float, Float ) -> GraticuleProperty

Set the extent of major graticule lines. The first parameter is a (longitude,latitude) pair defining the minimum extent, the second parameter the maximum extent.

grExtentMinor : ( Float, Float ) -> ( Float, Float ) -> GraticuleProperty

Set the extent of minor graticule lines. The first parameter is a (longitude,latitude) pair defining the minimum extent, the second parameter the maximum extent.

The precision of the graticule in degrees. If unspecified, the default of 2.5 degrees is used. Smaller values provide a less stepped appearance of curved lines but take longer to render.

Formatting Input Data

See the Vega-Lite format and JSON documentation.

CSV data file format (only necessary if the file extension does not indicate the type).

TSV data file format (only necessary if the file extension does not indicate the type).

dsv : Char -> Format

Delimited file format (DSV) with a given separator.

Apache arrow data file format. For example:

data =
    dataFromUrl "https://gicentre.github.io/data/scrabble.arrow" [ arrow ]
jsonProperty : String -> Format

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

A topoJSON feature format containing an object with the given name. For example,

geodata =
    dataFromUrl "https://gicentre.github.io/data/geoTutorials/londonBoroughs.json"
        [ topojsonFeature "boroughs" ]
topojsonMesh : String -> Format

A topoJSON mesh format containing an object with the given name. Unlike topojsonFeature, the corresponding geo data are returned as a single unified mesh, not as individual GeoJSON features.

parse : List ( String, DataType ) -> Format

Parsing rules when processing some data text, specified as a list of tuples in the form (fieldname, datatype). Useful when automatic type inference needs to be overridden, for example when converting strings to numbers:

data =
    dataFromUrl "myDataFile.csv"
        [ parse [ ( "x", foNum ), ( "y", foNum ) ] ]

Indicate numeric data type to be parsed when reading input data.

Indicate Boolean data type to be parsed when reading input data.

foDate : String -> DataType

Date format for parsing input data using D3's formatting specifiers or left as an empty string for default formatting.

foUtc : String -> DataType

Similar to foDate but for UTC format dates.

Creating the Transform Specification

Transformation rules are applied to data fields or geospatial coordinates before they are encoded visually.

transform : List LabelledSpec -> ( VLProperty, Spec )

Create a single transform from a list of transformation specifications. The order of transformations can be important, e.g. labels created with calculateAs, timeUnitAs and binAs that are used in other transformations. Using the functional composition pipeline idiom (as example below) allows you to provide the transformations in the order intended in a clear manner.

trans =
    transform
        << filter (fiExpr "datum.year == 2010")
        << calculateAs "datum.sex == 2 ? 'Female' : 'Male'" "gender"

Map projection used for geospatial coordinates.

Type of global map projection.

Projection’s clipping circle radius to the specified angle in degrees. A value of Nothing will switch to antimeridian cutting rather than small-circle clipping.

Projection’s viewport clip extent to the specified bounds in pixels.

prCenter : Float -> Float -> ProjectionProperty

Projection’s center as longitude and latitude in degrees.

A projection’s zoom scale, which if set, overrides automatic scaling of a geo feature to fit within the viewing area.

prTranslate : Float -> Float -> ProjectionProperty

A projection’s panning translation, which if set, overrides automatic positioning of a geo feature to fit within the viewing area.

prRotate : Float -> Float -> Float -> ProjectionProperty

A projection’s three-axis rotation angle. This should be in order lambda phi gamma specifying the rotation angles in degrees about each spherical axis.

Threshold for the projection’s adaptive resampling in pixels. Corresponds to the Douglas–Peucker distance. If precision is not specified, the projection’s current resampling precision of 0.707 is used.

'Hammer' map projection coefficient.

'Satellite' map projection distance.

Bottomley map projection fraction.

Number of lobes in lobed map projections such as the 'Berghaus star'.

Parallel for map projections such as the 'Armadillo'.

Radius value for map projections such as the 'Gingery'.

Ratio value for map projections such as the 'Hill'.

Reflect the x-coordinates after performing an identity projection. This creates a left-right mirror image of the geoshape marks when subject to an identity projection with identityProjection.

Reflect the y-coordinates after performing an identity projection. This creates a top-bottom mirror image of the geoshape marks when subject to an identity projection with identityProjection.

Spacing value for map projections such as the 'Lagrange'.

'Satellite' map projection tilt.

An Albers equal-area conic map projection.

An Albers USA map projection that combines continental USA with Alaska and Hawaii. Unlike other projection types, this remains unaffected by prRotate.

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 map projection that maps longitude to x and latitude to y. While showing less area distortion towards the poles than the default mercator projection, it is neither equal-area nor conformal.

A gnomonic map projection.

An 'identity' projection where longitude is projected directly to the x position and latitude to the y position. Can also reflect either of the coordinates by specifying prReflectX / prReflectY in the list of projection properties.

A Mercator map projection. This is the default projection of longitude,latitude values if no projection is set explicitly. It preserves shape (local angle) and lines of equal angular bearing remain parallel straight lines. But area is significantly enlarged towards the poles.

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 "winkel3").

Indicate no clipping to be applied.

clipRect : Float -> Float -> Float -> Float -> ClipRect

Clipping rectangle in pixel units. The four parameters are respectively 'left', 'top', 'right' and 'bottom' of the rectangular clipping bounds.

aggregate : List Spec -> List String -> List LabelledSpec -> List LabelledSpec

Aggregation transformations to be used when encoding channels. Useful when for applying the same transformation to a number of channels without defining it each time. The first parameter is a list of the named aggregation operations to apply. The second is a list of 'group by' fields.

trans =
    transform
        << aggregate
            [ opAs opMin "people" "lowerBound", opAs opMax "people" "upperBound" ]
            [ "age" ]
List Spec
-> List LabelledSpec
-> List LabelledSpec

Aggregation transformations to be used when encoding channels. Unlike aggregate, this transformation joins the results to the input data. Can be helpful for creating derived values that combine raw data with some aggregate measure, such as percentages of group totals. The first parameter is a list of the named aggregation operations to apply. The second is a list of possible window aggregate field properties, such as a field to group by when aggregating. The third parameter is a list of transformations to which this is added.

transform
    << joinAggregate [ opAs opMean "rating" "avYearRating" ]
        [ wiGroupBy [ "year" ] ]
    << filter (fiExpr "(datum.rating - datum.avYearRating) > 3")

For details, see the Vega-Lite joinaggregate documentation

opAs : Operation -> String -> String -> Spec

Aggregation operation. The first parameter is the operation to use; the second the name of the field in which to apply it and the third the name to be given to this transformation.

trans =
    transform
        << aggregate
            [ opAs opMin "people" "lowerBound"
            , opAs opMax "people" "upperBound"
            ]
            [ "age" ]

If the operation is Count, it does not apply to any specific field, so the second parameter can be an empty string.

timeUnitAs : TimeUnit -> String -> String -> List LabelledSpec -> List LabelledSpec

Create a new data field based on the given temporal binning. Unlike the direct encoding binning, this transformation is named and so can be referred to in multiple encodings. The first parameter is the width of each temporal bin, the second is the field to bin and the third is name to give the newly binned field.

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 aggregation 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.

-> String
-> String
-> List LabelledSpec
-> List LabelledSpec

Binning transformation that may be referenced in other transformations or encodings. The type of binning can be customised with a list of BinProperty generating functions (biBase, biDivide etc.) or an empty list to use the default binning.

trans =
    transform
        << binAs [ biMaxBins 3 ] "IMDB_Rating" "ratingGroup"

Note that usually, direct binning within an encoding is preferred over this form of bin transformation.

biBase : Float -> BinProperty

Number base to use for automatic bin determination (default is base 10).

biDivide : List Float -> BinProperty

Scale factors indicating allowable subdivisions for binning. The default value is [5, 2], which indicates that for base 10 numbers (the default base), binning will consider dividing bin sizes by 5 and/or 2.

biExtent : Float -> Float -> BinProperty

Desired range of bin values when binning a collection of values. The first and second parameters indicate the minimum and maximum range values.

Maximum number of bins when binning a collection of values.

Step size between bins when binning a collection of values.

Whether or not binning boundaries use human-friendly values such as multiples of ten.

biStep : Float -> BinProperty

Step size between bins when binning a collection of values.

biSteps : List Float -> BinProperty

Allowable step sizes between bins when binning a collection of values.

String
-> List String
-> String
-> String
-> List StackProperty
-> List LabelledSpec
-> List LabelledSpec

Apply a stack transform for positioning multiple values. This is an alternative to specifying stacking directly when encoding position. First parameter is the field to be stacked; the second the fields to group by; the third and fourth are the names to give the output field names; the fifth lists the optional offset and sort properties.

Stack offset when applying a stack transformation.

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

Offset a stacked layout using a central stack baseline.

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

Do not stack marks (produces a layered plot).

Ordering within a stack when applying a stack transformation.

Indicate that the given field should be sorted in ascending order.

Indicate that the given field should be sorted in descending order.

calculateAs : String -> String -> List LabelledSpec -> List LabelledSpec

Generate a new data field based on calculations from existing fields. The first parameter is an expression representing the calculation and the second is the name to give the newly calculated field.

trans =
    transform << calculateAs "datum.sex == 2 ? 'F' : 'M'" "gender"
filter : Filter -> List LabelledSpec -> List LabelledSpec

Apply a filter to a channel or field.

fiEqual : String -> DataValue -> Filter

Filter a data stream so that only data in a given field equal to the given value are used.

fiLessThan : String -> DataValue -> Filter

Filter a data stream so that only data in a given field less than the given value are used.

Filter a data stream so that only data in a given field less than or equal to the given value are used.

Filter a data stream so that only data in a given field greater than the given value are used.

Filter a data stream so that only data in a given field greater than or equal to the given value are used.

fiExpr : String -> Filter

Filter a data stream so that only data that satisfy the given predicate expression are used.

Build up a filtering predicate through logical composition (and, or etc.).

fiSelection : String -> Filter

Filter a data stream so that only data in a given field that are within the given interactive selection are used.

fiOneOf : String -> DataValues -> Filter

Filter a data stream so that only data in a given field contained in the given list of values are used.

fiRange : String -> FilterRange -> Filter

Filter a data stream so that only data in a given field that are within the given range are used.

fiValid : String -> Filter

Filter a data stream so that only valid data (i.e. not null or NaN) in a given field are used.

numRange : Float -> Float -> FilterRange

Minimum-maximum number range to be used in data filtering.

Min max date-time range to be used in data filtering. If either parameter is an empty list, it is assumed to be unbounded.

Flattening

See the Vega-Lite flatten and fold documentation.

flatten : List String -> List LabelledSpec -> List LabelledSpec

Map array-valued fields to a set of individual data objects, one per array entry.

flattenAs : List String -> List String -> List LabelledSpec -> List LabelledSpec

Similar to flatten but allows the new output fields to be named (second parameter).

fold : List String -> List LabelledSpec -> List LabelledSpec

Perform a gather operation to tidy a table. Collapse multiple data fields into two new data fields: key containing the original data field names and value containing the corresponding data values. This performs the same function as the 'gather' function in the Tidy Elm package and the pivot_longer / gather operation in the R tidyverse.

List String
-> String
-> String
-> List LabelledSpec
-> List LabelledSpec

Similar to fold but allows the new output key and value fields to be given alternative names.

Relational Joining (lookup)

See the Vega-Lite lookup documentation.

String
-> ( VLProperty, Spec )
-> String
-> List String
-> List LabelledSpec
-> List LabelledSpec

Perform a lookup of named fields between two data sources. This allows you to find values in one data source based on the values in another. The first parameter is the field in the primary data source to act as key, the second is the secondary data source which can be specified with a call to dataFromUrl or other data generating function. The third is the name of the field in the secondary data source to match values with the primary key. The fourth parameter is the list of fields to be stored when the keys match.

String
-> Data
-> String
-> String
-> List LabelledSpec
-> List LabelledSpec

Similar to lookup but returns the entire set of field values from the secondary data source when keys match. Accessed via the name provided in the fourth parameter.

Data Imputation

Impute missing data. See the Vega-Lite impute documentation.

String
-> String
-> List LabelledSpec
-> List LabelledSpec

Impute missing data values. The first parameter is the data field to process; the second the key field to uniquely identify data objects within a group; the third customisable options.

imFrame : Maybe Int -> Maybe Int -> ImputeProperty

1d window over which data imputation values are generated. The two parameters should either be Just a number indicating the offset from the current data object, or Nothing to indicate unbounded rows preceding or following the current data object.

Key values to be considered for imputation.

imKeyValSequence : Float -> Float -> Float -> ImputeProperty

Key values to be considered for imputation as a sequence of numbers between a start (first parameter), to less than an end (second parameter) in steps of the third parameter.

Imputation method to use when replacing values.

imGroupBy : List String -> ImputeProperty

Allow imputing of missing values on a per-group basis. For use with the impute transform only and not a channel encoding.

New value to use when imputing with imValue.

Use field value when imputing missing data.

Use mean of values when imputing missing data.

Use median of values when imputing missing data.

Use maximum of values when imputing missing data.

Use maximum of values when imputing missing data.

Data Sampling

See the Vega-Lite sample documentation

sample : Float -> List LabelledSpec -> List LabelledSpec

Randomly sample rows from a data source up to a given maximum.

Window Transformations

See the Vega-Lite window transform field and window transform documentation.

List ( List Window, String )
-> List LabelledSpec
-> List LabelledSpec

Window transform for performing calculations over sorted groups of data objects such as ranking, lead/lag analysis, running sums and averages.

The first parameter is a list of tuples each comprising a window transform field definition and an output name. The second is the window transform definition.

   trans =
       transform
           << window [ ( [ wiAggregateOp opSum, wiField "Time" ], "TotalTime" ) ]
               [ wiFrame Nothing Nothing ]

An aggregrate operation to be used in a window transformation.

Window-specific operation to be used in a window transformation.

wiParam : Int -> Window

Numeric parameter for window-only operations that can be parameterised (woPercentile, woLag, woLead and woNthValue).

wiField : String -> Window

Field for which to compute a window operation. Not needed for operations that do not apply to fields such as opCount, woRank and woDenseRank.

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.

wiFrame : Maybe Int -> Maybe Int -> WindowProperty

Moving window for use by a window transform. The two parameters should either be Just a number indicating the offset from the current data object, or Nothing to indicate unbounded rows preceding or following the current data object.

Whether or not the sliding window frame in a window transform should ignore peer values (those considered identical by the sort criteria).

wiGroupBy : List String -> WindowProperty

Fields for partitioning data objects in a window transform into separate windows. If unspecified, all points will be in a single group.

Comparator for sorting data objects within a window transform.

Indicate that the given field should be sorted in ascending order when performing a window transform.

Indicate that the given field should be sorted in descending order when performing a window transform.

Creating the Mark Specification

Functions for declaring the type of visual marks used in the visualization.

area : List MarkProperty -> ( VLProperty, Spec )

An area mark for representing a series of data elements, such as in a stacked area chart or streamgraph.

bar : List MarkProperty -> ( VLProperty, Spec )

Bar mark for histograms, bar charts etc.

boxplot : List MarkProperty -> ( VLProperty, Spec )

Boxplot composite mark for showing summaries of statistical distributions.

errorband : List MarkProperty -> ( VLProperty, Spec )

Errorband composite mark for showing summaries of variation along a signal. By default no border is drawn. To add a border with default properties use maBorders with an empty list.

errorbar : List MarkProperty -> ( VLProperty, Spec )

Errorbar composite mark for showing summaries of variation along a signal. By default no ticks are drawn. To add ticks with default properties use maTicks with an empty list.

circle : List MarkProperty -> ( VLProperty, Spec )

Circle mark for symbolising points.

geoshape : List MarkProperty -> ( VLProperty, Spec )

Geoshape determined by geographically referenced coordinates.

line : List MarkProperty -> ( VLProperty, Spec )

Line mark for symbolising a sequence of values.

point : List MarkProperty -> ( VLProperty, Spec )

Point mark for symbolising a data point with a symbol.

rule : List MarkProperty -> ( VLProperty, Spec )

Rule line connecting two vertices.

square : List MarkProperty -> ( VLProperty, Spec )

Square mark for symbolising points.

textMark : List MarkProperty -> ( VLProperty, Spec )

Text mark to be displayed at some point location.

tick : List MarkProperty -> ( VLProperty, Spec )

Short line (tick) mark for symbolising point locations.

trail : List MarkProperty -> ( VLProperty, Spec )

Trail mark (line with variable width along its length).

Horizontal alignment of a text mark.

Rotation angle in degrees of a text mark.

Band size of a bar mark.

Vertical alignment of a text mark.

Offset between bars for a binned field using a bar mark.

Border properties for an errorband mark.

Box symbol properties for the boxplot mark.

Whether or not a mark should be clipped to the enclosing group's dimensions.

maColor : String -> MarkProperty

Default color of a mark. Note that maFill and maStroke have higher precedence and will override this if specified.

Cursor to be associated with a hyperlink mark.

Extent of whiskers used in a boxplot, error bars or error bands.

maHRef : String -> MarkProperty

Hyperlink to be associated with a mark making it a clickable hyperlink.

Continuous band size of a bar mark.

Discrete band size of a bar mark.

maDx : Float -> MarkProperty

Horizontal offset between a text mark and its anchor.

maDy : Float -> MarkProperty

Vertical offset between a text mark and its anchor.

maFill : String -> MarkProperty

Default fill color of a mark.

Whether or not a mark's color should be used as the fill color instead of stroke color.

Fill opacity of a mark.

maFont : String -> MarkProperty

Font of a text mark. Can be any font name made accessible via a css file (or a generic font like serif, monospace etc.).

Font size in pixels used by a text mark.

Font style (e.g. italic) used by a text mark.

Font weight used by a text mark.

Interpolation method used by line and area marks.

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

Ordering of vertices in a line or area mark. If true (default), order is determined by measurement type or order channel. If false, the original data order is used.

Orientation of a non-stacked bar, tick, area or line mark.

Appearance of a point marker joining the vertices of a line or area mark.

Appearance of a line marker joining the vertices of an area mark.

Median line properties for the boxplot mark.

Outlier symbol properties for the boxplot mark.

Polar coordinate radial offset of a text mark from its origin.

Rule (main line) properties for the errorbar and boxplot marks.

Shape of a point mark.

Whether or not month and weekday names are abbreviated in a text mark.

maSize : Float -> MarkProperty

Size of a mark in square units.

Default stroke color of a mark.

Cap style of a mark's stroke.

Rounded stroke cap.

Square stroke cap.

Butt stroke cap.

maStrokeDash : List Float -> MarkProperty

Stroke dash style used by a mark. Determined by an alternating 'on-off' sequence of line lengths.

Number of pixels before the first line dash is drawn.

Line segment join style of a mark's stroke.

Rounded stroke join.

Bevelled stroke join.

Mitred stroke join.

Mitre limit at which to bevel a join between line segments of a mark's stroke.

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

Stroke width of a mark in pixel units.

maStyle : List String -> MarkProperty

Names of custom styles to apply to a mark. Each should refer to a named style defined in a separate style configuration.

Interpolation tension used when interpolating line and area marks.

maText : String -> MarkProperty

Placeholder text for a text mark for when a text channel is not specified.

Polar coordinate angle (clockwise from north in radians) of a text mark from the origin determined by its x and y properties.

Thickness of a tick mark.

Tick properties for the errorbar or boxplot mark.

Source of a mark's tooltip content.

maX : Float -> MarkProperty

X position of a mark.

maY : Float -> MarkProperty

Y position of a mark.

X position offset for a mark.

Y position offset for a mark.

maX2 : Float -> MarkProperty

X2 position (secondary x value for lines and areal marks).

maY2 : Float -> MarkProperty

Y2 position (secondary y value for lines and areal marks).

X2 position offset for a mark.

Y2 position offset for a mark.

Used by Mark Properties

Indicate horizontal mark orientation.

Indicate vertical mark orientation.

Cubic basis spline interpolation between points anchored at first and last points.

Open cubic basis spline interpolation between points, which may not intersect first and last points.

Closed cubic basis spline interpolation between points forming a polygon.

Bundle curve interpolation between points.

Cubic cardinal spline interpolation between points anchored at first and last points.

Open cubic cardinal spline interpolation between points, which may not intersect first and last points

Closed cubic cardinal spline interpolation between points forming a polygon.

Linear (straight) interpolation between points.

Cubic spline interpolation that preserves monotonicity between points.

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

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

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

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 triangular symbol for a shape mark.

Specify a downward triangular symbol for a shape mark.

symPath : String -> Symbol

A custom symbol shape as an SVG path description.

No point marker to be shown on a line or area mark.

Transparent point marker to be placed on area or line mark. Useful for interactive selections.

Properties of a point marker that is overlaid on a line or area mark.

Properties of a line marker that is overlaid on an area mark.

Indicates no line marker on an area mark.

Band extent between the minimum and maximum values in a distribution.

Band extent between the 95% confidence intervals of a distribution.

Band extent between the lower and upper quartiles of a distribution.

A scaling of the interquartile range to be used as whiskers in a boxplot. For example a value of 1.5 would extend whiskers to ±1.5x the IQR from the mean.

Band extent as the standard error about the mean of a distribution.

Band extent as the standard deviation of a distribution.

Indicate tooltips are generated by data.

Indicate tooltips are generated by encoding (default).

Indicate that tooltips should be disabled.

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.

Creating the Encoding Specification

Types and functions for declaring which data fields (data) are mapped to which channels (position, color etc.).

encoding : List LabelledSpec -> ( VLProperty, Spec )

Create an encoding specification from a list of channel encodings. These are commonly built by chaining series of LabelledSpec generating functions together. For example,

enc =
    encoding
        << position X [ pName "month", pMType Temporal ]
        << position Y [ pName "score", pMType Quantitative ]
        << color [ mName "team", mMType Nominal ]
= Nominal
| Ordinal
| Quantitative
| Temporal
| GeoFeature

Type of measurement to be associated with some channel.

Position channel

Relates to where something appears in the visualization. See the Vega-Lite position documentation

-> List LabelledSpec
-> List LabelledSpec

Encode a position channel. The first parameter identifies the channel, the second a list of encoding options.

= X
| Y
| X2
| Y2
| Longitude
| Latitude
| Longitude2
| Latitude2

Type of position channel.

Position Channel Properties

Name of the field used for encoding with a position channel.

Reference in a position channel to a field name generated by repeatFlow or repeat. The parameter identifies whether reference is being made to fields that are to be arranged in columns, in rows or a with a flow layout.

For example,

enc =
    encoding
        << position X [ pRepeat arFlow, pMType Quantitative ]


spec =
      asSpec [ data [], tick [], enc [] ]


toVegaLite
    [ repeatFlow [ "Horsepower", "Miles_per_Gallon", "Acceleration"]
    , specification spec
    ]

Level of measurement when encoding with a position channel.

Discretize numeric values into bins when encoding with a position channel.

Indicate that data encoded with position are already binned.

Form of time unit aggregation of field values when encoding with a position channel.

Title of a field when encoding with a position channel.

Compute some aggregate summary statistics for a field to be encoded with a position channel. The type of aggregation is determined by the given operation parameter.

Scaling applied to a field when encoding with a position channel. The scale will transform a field's value into a position along one axis.

Axis properties used when encoding with a position channel. For no axis, provide an empty list.

Sort order for field when encoding with a position channel.

Type of stacking offset for field when encoding with a position channel.

Set the position to the width of the enclosing data space. Useful for justifying a mark to the right hand edge of a view. e.g. to position a mark at the right of the data rectangle:

enc =
    encoding
        << position X [ pWidth ]

Set the position to the height of the enclosing data space. Useful for placing a mark relative to the bottom edge of a view.

Set a position to an arbitrary value. Useful for placing items at the top of a plot area (pNum 0) or a fixed number of pixels from the top.

Imputation rules for a position channel. See the Vega-Lite impute documentation

Properties Used by Position Channels

Sorting Properties

See the Vega-Lite sort documentation.

Indicate sorting is to be applied from low to high.

Indicate sorting is to be applied from high to low.

Sort by the aggregated summary of a given field using a given aggregation operation. e.g., sort the categorical data field variety by the mean age of the data in each variety category:

position Y
    [ pName "variety"
    , pMType Ordinal
    , pSort [ soByField "age" opMean, soDescending ]
    ]

Sort by another channel. For example,

position Y
    [ pName "age"
    , pMType Ordinal
    , pSort [ soByChannel chX ]
    ]

Sort by the aggregated summaries of the given fields (referenced by a repeat iterator) using a given aggregation operation.

Custom sort order listing data values explicitly.

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

Formatting pattern for axis labels. To distinguish between formatting as numeric values and data/time values, additionally use axFormatAsNum or axFormatAsTemporal.

Indicate that axis labels should be formatted as numbers. To control the precise numeric format, additionally use axFormat providing a d3 numeric format string.

Indicate that axis labels should be formatted as dates/times. To control the precise temporal format, additionally use axFormat providing a d3 date/time format string.

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

Rotation angle in degrees of axis labels.

Overlap strategy for labels when they are too large to fit within the space devoted to an axis.

Padding in pixels between an axis and its text labels.

Whether or not axis labels should be displayed.

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

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

Offset to displace the axis from the edge of the enclosing group or data rectangle.

Orientation of an axis relative to the plot it is describing.

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

Position of axis tick relative to a band (0 to 1).

axDates : List (List DateTime) -> AxisProperty

Dates/times to appear along an axis.

Color of axis domain line.

Opacity of axis domain line.

Width of axis domain line.

Horizontal alignment of axis tick labels.

Vertical alignment of axis tick labels.

axLabelBound : Maybe Float -> AxisProperty

How or if labels should be hidden if they exceed the axis range. If Nothing, no check for label size is made. A number specifies the permitted overflow in pixels.

Color of axis tick label.

axLabelFlush : Maybe Float -> AxisProperty

How or if labels at beginning or end of the axis should be aligned. Specifies the distance threshold from an end-point within which labels are flush-adjusted or if Nothing, no flush-adjustment made.

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

Font name of an axis label.

Font size of an axis label.

Font weight of an axis label.

Maximum length in pixels of axis tick labels.

Opacity of an axis label.

Color of axis ticks.

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).

Whether or not an extra axis tick should be added for the initial position of an axis.

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

Opacity of axis ticks.

Whether or not axis tick positions should be rounded to nearest integer.

Whether or not an axis should include tick marks.

Tick mark size in pixels.

The minimum desired step between axis ticks, in terms of scale domain values. For example, a value of 1 indicates that ticks should not be less than 1 unit apart. If specified, the tick count value will be adjusted, if necessary, to enforce the minimum step value.

Deprecated in favour of axTickMinStep.

Width of axis ticks.

axTitle : String -> AxisProperty

Title to display as part of an axis. An empty string can be used to prevent a title being displayed.

Horizontal alignment of an axis title.

Angle in degrees of an axis title.

Vertical alignment of axis title.

Color of axis title.

Font name for an axis title.

Font size for an axis title.

Font weight of an axis title.

Maximum length in pixels of axis title.

Opacity of an axis title.

Padding in pixels between a title and axis.

X position of an axis title relative to the axis group.

Y position of an axis title relative to the axis group.

axValues : List Float -> AxisProperty

Numeric values to appear along an axis.

Drawing order of the axis relative to the other chart elements. 1 indicates axis is drawn in front of chart marks, 0 indicates it is drawn behind them.

Positioning Constants

Text

Left horizontal text alignment.

Center horizontal text alignment.

Right horizontal text alignment.

Top vertical text alignment.

Middle vertical text alignment.

Bottom vertical text alignment.

Overlapping text

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

Greedy 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.

Legends

Top side, used to specify an axis position.

Bottom side, used to specify an axis position.

Left side, used to specify an axis position.

Right side, used to specify an axis position.

Mark channels

Relate to the appearance of the visual marks in the visualization such as their color or size.

size : List MarkChannel -> List LabelledSpec -> List LabelledSpec

Encode a size channel with a list of mark channel properties.

color : List MarkChannel -> List LabelledSpec -> List LabelledSpec

Encode a color channel. The first parameter is a list of mark channel properties that characterise the way a data field is encoded by color.

fill : List MarkChannel -> List LabelledSpec -> List LabelledSpec

Encode a fill channel. This acts in a similar way to encoding by color but only affects the interior of closed shapes. If both fill and color encodings are specified, fill takes precedence.

stroke : List MarkChannel -> List LabelledSpec -> List LabelledSpec

Encode a stroke channel. This acts in a similar way to encoding by color but only affects the exterior boundary of marks.

strokeWidth : List MarkChannel -> List LabelledSpec -> List LabelledSpec

Encode a stroke width channel.

opacity : List MarkChannel -> List LabelledSpec -> List LabelledSpec

Encode an opacity channel.

fillOpacity : List MarkChannel -> List LabelledSpec -> List LabelledSpec

Encode a fill opacity channel. This acts in a similar way to encoding by opacity but only affects the interior of closed shapes. If both fillOpacity and opacity encodings are specified, fillOpacity takes precedence.

strokeOpacity : List MarkChannel -> List LabelledSpec -> List LabelledSpec

Encode a stroke opacity channel. This acts in a similar way to encoding by opacity but only affects the exterior boundary of marks. If both opacity and strokeOpacity are specified, strokeOpacity takes precedence for stroke encoding.

shape : List MarkChannel -> List LabelledSpec -> List LabelledSpec

Encode a shape channel.

Mark Channel Properties

mName : String -> MarkChannel

Field used for encoding with a mark property channel.

Reference in a mark channel to a field name generated by repeatFlow or repeat. The parameter identifies whether reference is being made to fields that are to be arranged in columns, in rows or a with a flow layout.

Level of measurement when encoding with a mark property channel.

Scaling applied to a field when encoding with a mark property channel. The scale will transform a field's value into a color, shape, size etc.

Discretize numeric values into bins when encoding with a mark property channel.

Indicate that data encoding with a mark are already binned.

Imputation rules for a mark channel. See the Vega-Lite impute documentation

Time unit aggregation of field values when encoding with a mark property channel.

mTitle : String -> MarkChannel

Title of a field when encoding with a mark property channel.

Compute some aggregate summary statistics for a field to be encoded with a mark property channel. The type of aggregation is determined by the given operation parameter.

Properties of a legend that describes a mark's encoding. For no legend, provide an empty list as a parameter.

mPath : String -> MarkChannel

SVG path string used when encoding with a mark property channel. Useful for providing custom shapes.

mNum : Float -> MarkChannel

Literal numeric value when encoding with a mark property channel.

mStr : String -> MarkChannel

Literal string value when encoding with a mark property channel.

mBoo : Bool -> MarkChannel

Boolean value when encoding with a mark property channel.

A gradient legend for continuous quantitative data.

A symbol legend for categorical data.

Limit height of legend entries.

Horizontal padding between symbol legend entries.

Number of columns in which to arrange symbol legend entries.

Legend corner radius.

Direction of a legend.

Legend background color.

Formatting pattern for legend values. To distinguish between formatting as numeric values and data/time values, additionally use leFormatAsNum or leFormatAsTemporal.

Indicate that legend labels should be formatted as numbers. To control the precise numeric format, additionally use leFormat providing a d3 numeric format string.

Indicate that legend labels should be formatted as dates/times. To control the precise temporal format, additionally use leFormat providing a d3 date/time format string.

Length in pixels of the primary axis of a color ramp legend.

Thickness in pixels of a color ramp legend.

Color for strokes in a color ramp legend.

Width for strokes in a color ramp legend.

Alignment to apply to symbol legends rows and columns.

Horizontal alignment of legend labels.

Vertical alignment of legend labels.

Color for legend labels.

Font for legend labels.

Font size legend labels.

Maximum width for legend labels in pixel units.

Offset for legend labels.

Strategy for resolving overlapping legend labels.

Offset in pixels of a legend from the encoded marks it describes. If the legend orientation is one of loTop, loBottom, loLeft or loRight, a positive offset moves the legend outwards away from the encoded marks. If it is one of loTopLeft, loTopRight, loBottomLeft or loBottomRight a positive offset will move it inwards away from the corner. If loNone, the offset has no effect.

Position of a legend in a scene.

Padding in pixels between a legend and axis.

Vertical spacing in pixel units between a symbol legend entries.

Legend border color.

Legend border stroke width.

Legend symbol fill color.

Legend symbol size.

Legend symbol outline color.

Legend symbol stroke width.

Legend symbol type.

Number of tick marks in a quantitative legend.

Title of a legend.

Horizontal alignment for legend titles.

Vertical alignment for legend titles.

Color for legend title.

Font for legend titles.

Font size for legend titles.

Font weight for legend titles.

Maximum size in pixel units for legend titles.

Spacing in pixel units between title and legend.

Type of legend.

An explicit set of legend values.

Drawing order of a legend relative to other chart elements. To place a legend in front of others use a positive integer, or 0 to draw behind.

Position legend to the left of the visualization it describes.

Position legend outside and to the right of the visualization it describes.

Position legend outside and above the visualization it describes.

Position legend outside and below the visualization it describes.

Position legend within the visualization it describes in the top-left corner.

Position legend within the visualization it describes in the top-right corner.

Position legend within the visualization it describes in the bottom-left corner.

Position legend within the visualization it describes in the bottom-right corner.

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

leNums : List Float -> LegendValues

An explicit set of numeric legend values.

leStrs : List String -> LegendValues

An explicit set of legend strings.

leDts : List (List DateTime) -> LegendValues

An explicit set of legend date-times.

Text Channels

Relate to the appearance of the text and tooltip elements of the visualization. See the Vega-Lite text documentation

text : List TextChannel -> List LabelledSpec -> List LabelledSpec

Encode a text channel.

tooltip : List TextChannel -> List LabelledSpec -> List LabelledSpec

Encode a tooltip channel. To encode multiple tooltip values with a mark, use tooltips.

tooltips : List (List TextChannel) -> List LabelledSpec -> List LabelledSpec

Encode a tooltip channel with multiple tooltips. The first parameter is a list of the multiple tooltips, each of which is a list of text channel properties that define the channel.

tName : String -> TextChannel

Name of the field used for encoding with a text channel.

Reference in a text channel to a field name generated by repeatFlow or repeat. The parameter identifies whether reference is being made to fields that are to be arranged in columns, in rows or a with a flow layout.

Level of measurement when encoding with a text channel.

Discretize numeric values into bins when encoding with a text channel.

Indicate that data encoded with a text channel are already binned.

Compute some aggregate summary statistics for a field to be encoded with a text channel. The type of aggregation is determined by the given operation parameter.

Time unit aggregation of field values when encoding with a text channel.

tTitle : String -> TextChannel

Title of a field when encoding with a text or tooltip channel.

tFormat : String -> TextChannel

Formatting pattern for text marks. To distinguish between formatting as numeric values and data/time values, additionally use tFormatAsNum or tFormatAsTemporal.

Indicate that values encoded with a text channel should be formatted as numbers. To control the precise numeric format, additionally use tFormat providing a d3 numeric format string.

Indicate that values encoded with a text channel should be formatted as dates/times. To control the precise temporal format, additionally use tFormat providing a d3 date/time format string.

= Bold
| Bolder
| Lighter
| Normal
| W100
| W200
| W300
| W400
| W500
| W600
| W700
| W800
| W900

Weight options for a font.

Relates to a clickable URL destination of a mark. Unlike most other channels, the hyperlink channel has no direct visual expression other than the option of changing the cursor style when hovering, so an encoding will usually pair hyperlinks with other visual channels such as marks or texts. See the Vega-Lite hyperlink documentation

Field used for encoding with a hyperlink channel.

Reference in a hyperlink channel to a field name generated by repeatFlow or repeat. The parameter identifies whether reference is being made to fields that are to be arranged in columns, in rows or a with a flow layout.

Level of measurement when encoding with a hyperlink channel.

Discretize numeric values into bins when encoding with a hyperlink channel.

Indicate that data encoded with a hyperlink channel are already binned.

Compute some aggregate summary statistics for a field to be encoded with a hyperlink channel. The type of aggregation is determined by the given operation parameter.

Time unit aggregation of field values when encoding with a hyperlink channel.

Literal string value when encoding with a hyperlink channel.

Order channels

Channels that relate to the order of data fields such as for sorting stacking order or order of data points in a connected scatterplot. See the Vega-Lite order documentation.

order : List OrderChannel -> List LabelledSpec -> List LabelledSpec

Encode an order channel with a list of order field definitions.

oName : String -> OrderChannel

Name of the field used for encoding with an order channel.

Reference in a order channel to a field name generated by repeatFlow or repeat. The parameter identifies whether reference is being made to fields that are to be arranged in columns, in rows or a with a flow layout.

Level of measurement when encoding with an order channel.

Discretize numeric values into bins when encoding with an order channel.

Compute some aggregate summary statistics for a field to be encoded with an order channel. The type of aggregation is determined by the given operation parameter.

Sort order to be used by an order channel.

Time unit aggregation of field values when encoding with an order channel.

Facet channels

Channels for faceting single plots into small multiples. Can be used to create trellis plots or other arrangements in rows and columns. See the Vega-Lite facet documentation. See also, 'faceted view composition' for a more flexible (but more verbose) way of defining faceted views.

row : List FacetChannel -> List LabelledSpec -> List LabelledSpec

Encode a new facet to be arranged in rows. The first parameter is a list of facet properties that define the faceting channel. See the Vega-Lite row documentation

column : List FacetChannel -> List LabelledSpec -> List LabelledSpec

Encodes a new facet to be arranged in columns. The first parameter is a list of properties that define the faceting channel. This should include at least the name of the data field and its measurement type. See the Vega-Lite column documentation

Level of detail Channel

Used for grouping data but without changing the visual appearance of a mark. When, for example, a field is encoded by color, all data items with the same value for that field are given the same color. When a detail channel encodes a field, all data items with the same value are placed in the same group. See the Vega-Lite documentation.

detail : List DetailChannel -> List LabelledSpec -> List LabelledSpec

Encode a 'level of detail' channel. This provides a way of grouping by a field but unlike, say color, all groups have the same visual properties. The first parameter is a list of the field characteristics to be grouped.

dName : String -> DetailChannel

Field used for encoding with a level of detail (grouping) channel.

Level of measurement when encoding with a level of detail (grouping) channel.

Compute some aggregate summary statistics for a field to be encoded with a level of detail (grouping) channel. The type of aggregation is determined by the given operation parameter.

Discretize numeric values into bins when encoding with a level of detail (grouping) channel.

Set the imputation rules for a detail channel. See the Vega-Lite impute documentation

Form of time unit aggregation of field values when encoding with a level of detail (grouping) channel.

Scaling

Used to specify how the encoding of a data field should be applied. See the Vega-Lite scale documentation.

Type of scaling to apply.

Custom scaling domain.

Range of a scaling. The type of range depends on the encoding channel.

scScheme : String -> List Float -> ScaleProperty

Color scheme used by a color scaling. The first parameter is the name of the scheme (e.g. "viridis") and the second an optional specification of the number of colors to use (list of one number), or the extent of the color range to use (list of two numbers between 0 and 1).

Padding in pixels to apply to a scaling.

Inner padding to apply to a band scaling.

Outer padding to apply to a band scaling.

scRangeStep : Maybe Float -> ScaleProperty

Distance between the starts of adjacent bands in a band scaling. If Nothing is provided the distance is determined automatically.

Whether or not numeric values in a scaling are rounded to integers.

Whether or not values outside the data domain are clamped to the minimum or maximum value.

Interpolation method for scaling range values.

'Nice' minimum and maximum values in a scaling (e.g. multiples of 10).

Whether or not a numeric scaling should be forced to include a zero value.

Reverse the order of a scaling.

A band scale.

A linear band scale.

An ordinal band scale.

A linear scale.

A log scale. Defaults to log of base 10, but can be customised by setting scBase to some other value.

A symmetrical log scale. Similar to a log scale but supports zero and negative values. The slope of the function at zero can be set with scConstant.

The desired desired slope of the scSymLog function at zero. If unspecified, the default is 1.

The base to use for log scaling.

An ordinal scale.

A point scale.

A power scale. The exponent to use for scaling is specified with scExponent.

The exponent to use for power scaling.

A quantile scale.

A quantizing scale.

Deprecated in favour of scLinear.

A square root scale.

A threshold scale.

A temporal scale.

A UTC temporal scale.

raName : String -> ScaleRange

Name of a pre-defined scale range (e.g. symbol or diverging).

raNums : List Float -> ScaleRange

Numeric scale range. Depending on the scaling this may be a [min, max] pair, or a list of explicit numerical values.

raStrs : List String -> ScaleRange

Text scale range for discrete scales.

categoricalDomainMap : List ( String, String ) -> List ScaleProperty

Create a set of discrete domain to color mappings suitable for customising categorical scales. The first item in each tuple should be a domain value and the second the color value with which it should be associated. It is a convenience function equivalent to specifying separate scDomain and scRange lists and is safer as it guarantees a one-to-one correspondence between domain and range values.

color
    [ mName "weather"
    , mMType Nominal
    , mScale <|
        categoricalDomainMap
            [ ( "sun", "yellow" )
            , ( "rain", "blue" )
            , ( "fog", "grey" )
            ]
    ]
domainRangeMap : ( Float, String ) -> ( Float, String ) -> List ScaleProperty

Create a pair of continuous domain to color mappings suitable for customising ordered scales. The first parameter is a tuple representing the mapping of the lowest numeric value in the domain to its equivalent color; the second tuple the mapping of the highest numeric value to color. If the domain contains any values between these lower and upper bounds they are interpolated according to the scale's interpolation function. Convenience function equivalent to specifying separate scDomain and scRange lists and is safer as it guarantees a one-to-one correspondence between domain and range values.

color
    [ mName "year"
    , mMType Ordinal
    , mScale (domainRangeMap ( 1955, "#e6959c" ) ( 2000, "#911a24" ))
    ]
doNums : List Float -> ScaleDomain

Numeric values that define a scale domain.

doStrs : List String -> ScaleDomain

String values that define a scale domain.

doDts : List (List DateTime) -> ScaleDomain

Date-time values that define a scale domain.

Specify an unaggregated scale domain (type of data in scale).

Scale domain based on a named interactive selection.

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.

Color Scaling

For color interpolation types, see the Vega-Lite continuous scale documentation.

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

Long-path cube helix color interpolation for continuous color scales using the given gamma value (anchored at 1).

HCL color interpolation for continuous color scales.

HCL color interpolation in polar coordinate space for continuous color scales.

HSL color interpolation for continuous color scales.

HSL color interpolation in polar coordinate space for continuous color scales.

Lab color interpolation for continuous color scales.

rgb : Float -> CInterpolate

RGB color interpolation for continuous color scales using the given gamma value (anchored at 1).

Creating view compositions

Views can be combined to create more complex multiview displays. This may involve layering views on top of each other (superposition) or laying them out in adjacent spaces (juxtaposition using repeatFlow, repeat, facetFlow, facet, concat, hConcat or vConcat). Where different views have potentially conflicting channels (e.g. two position scales in a layered visualization) the rules for resolving them can be defined with resolve. For details, see the Vega-Lite composition documentation

layer : List Spec -> ( VLProperty, Spec )

Assign a list of specifications to superposed layers in a visualization.

concat : List Spec -> ( VLProperty, Spec )

Specifications to be juxtaposed in a flow layout of views.

columns : Maybe Int -> ( VLProperty, Spec )

Maximum number of columns to include in a view composition flow layout. If the number of faceted small multiples exceeds this number, flow moves to the next row. Only applies to flow layouts generated by concat, facetFlow and repeatFlow. If Nothing or not defined, faceted small multiples will be arranged in a single row.

hConcat : List Spec -> ( VLProperty, Spec )

Specifications to be juxtaposed horizontally in a column layout of views.

vConcat : List Spec -> ( VLProperty, Spec )

Specifications to be juxtaposed vertically in a row layout of views.

Alignment to apply to grid rows and columns generated by a composition operator. This version sets the same alignment for rows and columns.

Similar to align but with independent alignments for rows (first parameter) and columns (second parameter).

Subviews in a composed view to be aligned into a clean grid structure where all rows and columns are of the same size (based on maximum subview size).

Subviews in a composed view to be aligned into a clean grid structure where each row or column may be of variable size.

Flow layout is to be applied to composed views, in which adjacent subviews are placed one after the other.

bounds : Bounds -> ( VLProperty, Spec )

Bounds calculation method to use for determining the extent of a sub-plot in a composed view. If set to Full the entire calculated bounds including axes, title and legend are used; if Flush only the width and height values for the sub-view will be used.

Bounds calculation should use the entire plot area (including axes, title, and legend).

Bounds calculation should take only the specified width and height values for a sub-view. Useful when attempting to place sub-plots without axes or legends into a uniform grid structure.

spacing : Float -> ( VLProperty, Spec )

Spacing between sub-views in a composition operator.

spacingRC : Float -> Float -> ( VLProperty, Spec )

Similar to spacing but with independent spacing for rows (first parameter) and columns (second parameter).

center : Bool -> ( VLProperty, Spec )

Whether or not sub-views specified in a composition operator should be centred relative to their respective rows and columns.

centerRC : Bool -> Bool -> ( VLProperty, Spec )

Similar to center but with independent centring for rows and columns.

Resolution

Controlling the (in)dependence between composed views. See the Vega-Lite resolve documentation.

resolve : List LabelledSpec -> ( VLProperty, Spec )

Determine whether scales, axes or legends in composite views should share channel encodings.

resolution : Resolve -> List LabelledSpec -> List LabelledSpec

Define a resolution option to be applied when scales, axes or legends in composite views share channel encodings. For example, it allows different color scales to be used in a layered view, or different axis scales to be used in a faceted view. Each resolution rule should be in a tuple pairing the channel to which it applies and the rule type. The first parameter identifies the type of resolution.

resolve
    << resolution (reScale [ ( chY, reIndependent ) ])
    << resolution (reScale [ ( chColor, reIndependent ) ])
    << resolution (reLegend [ ( chShape, reShared ) ])

Scale domain should be shared with others in a composite visualization.

Scale domain should be independent of others in a composite visualization.

Indicate how a channel's axes should be resolved when defined in more than one view in a composite visualization.

Indicate how a channel's legends should be resolved when defined in more than one view in a composite visualization.

Indicate how a channel's scales should be resolved when defined in more than one view in a composite visualization.

X-channel to be used in a resolution specification

Y-channel to be used in a resolution specification

X2-channel to be used in a resolution specification

Y2-channel to be used in a resolution specification

Color channel to be used in a resolution specification

Opacity channel to be used in a resolution specification

Shape channel to be used in a resolution specification

Size channel to be used in a resolution specification

Faceted views

Small multiples each of which show subsets of the same dataset. The specification determines which field should be used to determine subsets along with their spatial arrangement. See the Vega-Lite facet documentation

repeatFlow : List String -> ( VLProperty, Spec )

Define the fields that will be used to compose a flow layout of a set of small multiples. Used when the encoding is largely identical, but the data field used in each might vary. When a list of fields is identified with repeat you also need to define a full specification to apply to each of those fields using asSpec.

Small multiples will be laid out from left to right, moving on to new rows only if the number of plots exceeds an optional column limit (specified via columns).

spec = asSpec [...]
toVegaLite
    [ repeatFlow [ "Cat", "Dog", "Fish" ]
    , specification spec
    ]
repeat : List RepeatFields -> ( VLProperty, Spec )

Define the fields that will be used to compose rows and columns of a set of small multiples. Similar to repeatFlow except that the fields for repetition by rows or by columns are set explicitly.

spec = asSpec [...]
toVegaLite
    [ repeat [ columnFields [ "Cat", "Dog", "Fish" ] ]
    , specification spec
    ]
rowFields : List String -> RepeatFields

Create a list of fields to use in set of repeated small multiples arranged in rows. The list of fields named here can be referenced in an encoding with pRepeat row, mRepeat row etc.

columnFields : List String -> RepeatFields

Create a list of fields to use in set of repeated small multiples arranged in columns. The list of fields named here can be referenced in an encoding with pRepeat column, mRepeat column etc.

facetFlow : List FacetChannel -> ( VLProperty, Spec )

Facet a view to create small multiples in a flow layout. Used when the encoding of the visualization in small multiples is identical, but data for each is grouped by the given fields. When creating a faceted view in this way you also need to define a full specification to apply to each of those facets using asSpec.

Small multiples will be laid out from left to right, moving on to new rows only if the number of plots exceeds an optional column limit (specified via columns).

spec = ...
toVegaLite
    [ facetflow [ fName "Origin", fMType Nominal ]
    , specification spec
    ]
facet : List FacetMapping -> ( VLProperty, Spec )

Facet a view to create a grid of small multiples. Similar to facetFlow except that the fields for faceting by rows and by columns are set explicitly.

spec = ...
toVegaLite
    [ facet [ rowBy [ fName "month", fMType Ordinal ]
            , columnBy [ fName "week", fMType Ordinal ]
            ]
    , specification spec
    ]

The mapping between a column and its field definitions in a set of faceted small multiples. This is used when specifying a more flexible facet rather than the compact, but simplified, column.

The mapping between a row and its field definitions in a set of faceted small multiples. This is used when specifying a more flexible facet rather than the compact, but simplified, row.

fName : String -> FacetChannel

Field used for encoding with a facet channel.

Level of measurement when encoding with a facet channel.

Compute some aggregate summary statistics for a field to be encoded with a facet channel. The type of aggregation is determined by the given operation parameter.

Discretize numeric values into bins when encoding with a facet channel.

Sort order for a field when encoding with a faceted channel. For example,

row
    [ fName "site"
    , fMType Ordinal
    , fSort [ soByField "x" opMedian, soDescending ]
    ]

Guide that spans a collection of faceted plots, each of which may have their own axes.

Form of time unit aggregation of field values when encoding with a facet channel.

asSpec : List ( VLProperty, Spec ) -> Spec

Create a specification sufficient to define an element in a composed visualization such as a superposed layer or juxtaposed facet. Typically a layer will contain a full set of specifications that define a visualization with the exception of the data specification which is usually defined outside of any one layer. For repeated and faceted specs, the entire specification is provided.

specification : Spec -> ( VLProperty, Spec )

Define a specification object for use with faceted and repeated small multiples.

spec = ...
toVegaLite
    [ facet [ rowBy [ fName "Origin", fMType Nominal ] ]
    , specification spec
    ]

Flow arrangement in a repeated/faceted view.

Column arrangement in a repeated/faceted view.

Row arrangement in a repeated/faceted view.

Header label rotation angle (in degrees) for a faceted view. A 'label' is the title for each sub-plot in a faceted view.

Horizontal alignment of header labels. A 'label' is the title for each sub-plot in a faceted view.

Anchor position of header labels. A 'label' is the title for each sub-plot in a faceted view.

Header label text color for a faceted view.

Header label font for a faceted view.

Header label font size for a faceted view.

Maximum length of a header label in a faceted view.

The position of a header label relative to a sub-plot. A 'label' is the title for each sub-plot in a faceted view.

Spacing in pixels between facet labels and the main plot area.

Header title in a faceted view. A 'title' is the overall title describing the collection of faceted plots.

Horizontal alignment of header title in a faceted view.

Anchor position of a header title in a faceted view.

Text angle of a header title in a faceted view.

Vertical alignment of a header title in a faceted view.

Text color of a header title in a faceted view.

Title font in a faceted view.

Title font weight in a faceted view.

Title font size in a faceted view.

Maximum length of a header title in a faceted view.

The position of a header title relative to a group of sub-plots in a faceted view.

Spacing in pixels between the main facet title and labels.

Formatting pattern for facet header (title) values. To distinguish between formatting as numeric values and data/time values, additionally use hdFormatAsNum or hdFormatAsTemporal.

Indicate that facet headers should be formatted as numbers. To control the precise numeric format, additionally use hdFormat providing a d3 numeric format string.

Indicate that facet headers should be formatted as dates/times. To control the precise temporal format, additionally use hdFormat providing a d3 date/time format string.

Creating Selections for Interaction

Selections allow a visualization to respond to interactions (such as clicking or dragging). They transform interactions into data queries. See the Vega-Lite selection and bind documentation.

selection : List LabelledSpec -> ( VLProperty, Spec )

Create a full selection specification from a list of selections.

sel =
    selection
        << select "view" seInterval [ seBindScales ] []
        << select "myBrush" seInterval []
        << select "myPaintbrush" seMulti [ seOn "mouseover", seNearest True ]
String
-> List LabelledSpec
-> List LabelledSpec

Create a single named selection that may be applied to a data query or transformation. The first two parameters specify the name to be given to the selection for later reference and the type of selection made. The third allows additional selection options to be specified.

Indicate a single, mark at a time, interactive selection can be made.

Indicate multiple interactive mark selections can be made (e.g. with shift-click).

Indicate a draggable bounding rectangle can be made for selecting all items that intersect with it.

Make a selection empty by default when nothing selected.

Vega event stream selector that can clear a selection. For example, to allow a zoomed/panned view to be reset on shift-click:

selection
    << select "myZoomPan"
        seInterval
        [ seBindScales, seClear "click[event.shiftKey]" ]

To remove the default clearing behaviour of a selection, provide an empty string rather than an event stream selector.

Binding to some input elements as part of a named selection.

seInit : List ( String, DataValue ) -> SelectionProperty

Initialise one or more selections with values from bound fields. For example,

sel =
    selection
        << select "CylYr"
            seSingle
            [ seFields [ "Cylinders", "Year" ]
            , seInit
                [ ( "Cylinders", num 4 )
                , ( "Year", num 1977 )
                ]
            , seBind
                [ iRange "Cylinders" [ inName "Cylinders ", inMin 3, inMax 8, inStep 1 ]
                , iRange "Year" [ inName "Year ", inMin 1969, inMax 1981, inStep 1 ]
                ]
            ]

Enable two-way binding between a selection and the scales used in the same view.

Encoding channels that form a named selection.

seFields : List String -> SelectionProperty

Field names for projecting a selection.

Whether or not a selection should capture nearest marks to a pointer rather than an exact position match.

Vega event stream selector that triggers a selection.

Strategy that determines how selections’ data queries are resolved when applied in a filter transform, conditional encoding rule, or scale domain.

Appearance of an interval selection mark (dragged rectangle).

Predicate expression that determines a toggled selection. See the Vega-Lite toggle documentation

Translation selection transformation used for panning a view. See the Vega-Lite translate documentation

Zooming selection transformation used for zooming a view. See the Vega-Lite zoom documentation

iRange : String -> List InputProperty -> Binding

Range slider input element that can bound to a named field value.

iCheckbox : String -> List InputProperty -> Binding

Checkbox input element that can bound to a named field value.

iRadio : String -> List InputProperty -> Binding

Radio box input element that can bound to a named field value.

iSelect : String -> List InputProperty -> Binding

Select input element that can bound to a named field value.

iText : String -> List InputProperty -> Binding

Text input element that can bound to a named field value.

iNumber : String -> List InputProperty -> Binding

Number input element that can bound to a named field value.

iDate : String -> List InputProperty -> Binding

Date input element that can bound to a named field value.

iTime : String -> List InputProperty -> Binding

Time input element that can bound to a named field value.

iMonth : String -> List InputProperty -> Binding

Month input element that can bound to a named field value.

iWeek : String -> List InputProperty -> Binding

Week input element that can bound to a named field value.

Local time input element that can bound to a named field value.

iTel : String -> List InputProperty -> Binding

Telephone number input element that can bound to a named field value.

iColor : String -> List InputProperty -> Binding

Color input element that can bound to a named field value.

Delay to introduce when processing input events in order to avoid unnecessary event broadcasting.

CSS selector indicating the parent element to which an input element should be added. Allows the option of the input element to be outside the visualization container.

inOptions : List String -> InputProperty

Options for a radio or select input element.

inMin : Float -> InputProperty

Minimum slider value for a range input element.

inMax : Float -> InputProperty

Maximum slider value for a range input element.

inName : String -> InputProperty

Custom label for a radio or select input element.

Minimum input element range slider increment.

Initial place-holding text for input elements such as text fields.

Fill color of an interval selection mark (dragged rectangular area).

Fill opacity of an interval selection mark in the range 0 to 1.

Stroke color of an interval selection mark.

Stroke dash style of an interval selection mark.

Stroke dash offset of an interval selection mark.

Stroke opacity of an interval selection mark in the range 0 to 1.

Stroke width of an interval selection mark.

Selection Resolution

Determines how selections are made across multiple views. See the Vega-lite resolve selection documentation.

One selection available across all subviews (default).

Each subview contains its own brush and marks are selected if they lie within any of these individual selections.

Each subview contains its own brush and marks are selected if they lie within all of these individual selections.

Making conditional channel encodings

To make channel encoding conditional on the result of some interaction, use mSelectionCondition (and its 't' and 'h' variants). Similarly mDataCondition (and its 't' and 'h' variants) will encode a mark conditionally depending on some data properties such as whether a datum is null or an outlier.

For interaction, once a selection has been defined and named, supplying a set of encodings allow mark encodings to become dependent on that selection. mSelectionCondition is followed firstly a (Boolean) selection and then an encoding if that selection is true and another encoding to be applied if it is false. The color specification below states "whenever data marks are selected with an interval mouse drag, encode the cylinder field with an ordinal color scheme, otherwise make them grey":

sel =
    selection << select "myBrush" Interval []


enc =
    encoding
        << position X [ pName "Horsepower", pMType Quantitative ]
        << position Y [ pName "Miles_per_Gallon", pMType Quantitative ]
        << color
            [ mSelectionCondition (selectionName "myBrush")
                [ mName "Cylinders", mMType Ordinal ]
                [ mStr "grey" ]
            ]

In a similar way, mDataCondition will encode a mark depending on whether any predicate tests are satisfied. Unlike selections, multiple conditions and associated encodings can be specified. Each test condition is evaluated in order and only on failure of the test does encoding proceed to the next test. If no tests are true, the encoding in the final parameter is applied in a similar way to 'case of' expressions:

enc =
    encoding
        << position X [ pName "value", pMType Ordinal ]
        << color
            [ mDataCondition
                [ ( expr "datum.value < 40", [ mStr "blue" ] )
                , ( expr "datum.value < 50", [ mStr "red" ] )
                , ( expr "datum.value < 60", [ mStr "yellow" ] )
                ]
                [ mStr "black" ]
            ]

See the Vega-Lite documentation.

Make a mark channel conditional on interactive selection. The first parameter is a selection condition to evaluate; the second the encoding to apply if that selection is true; the third parameter is the encoding if the selection is false.

color
    [ mSelectionCondition (selectionName "myBrush")
        [ mName "myField", mMType Ordinal ]
        [ mStr "grey" ]
    ]

Make a mark channel conditional on one or more predicate expressions. The first parameter is a list of tuples each pairing a test condition with the encoding if that condition evaluates to true. The second is the encoding if none of the tests are true.

color
    [ mDataCondition [ ( expr "datum.myField === null", [ mStr "grey" ] ) ]
        [ mStr "black" ]
    ]

Make a text channel conditional on interactive selection. The first parameter is a selection condition to evaluate; the second the encoding to apply if that selection is true; the third parameter is the encoding if the selection is false.

Make a text channel conditional on one or more predicate expressions. The first parameter is a list of tuples each pairing an expression to evaluate with the encoding if that expression is true. The second is the encoding if none of the expressions are evaluated as true.

Make a hyperlink channel conditional on some predicate expression. The first parameter provides the expression to evaluate, the second the encoding to apply if the expression is true, the third the encoding if the expression is false.

Make a hyperlink channel conditional on interactive selection. The first parameter provides the selection to evaluate, the second the encoding to apply if the hyperlink has been selected, the third the encoding if it is not selected.

Apply an 'and' Boolean operation as part of a logical composition.

and (expr "datum.IMDB_Rating === null") (expr "datum.Rotten_Tomatoes_Rating === null")

Apply an 'or' Boolean operation as part of a logical composition.

Apply a negation Boolean operation as part of a logical composition. Boolean operations can be nested to any level.

not (and (expr "datum.IMDB_Rating === null") (expr "datum.Rotten_Tomatoes_Rating === null"))
expr : String -> BooleanOp

Expression that should evaluate to either true or false. Can use any valid Vega expression.

selected : String -> BooleanOp

Interactive selection that will be true or false as part of a logical composition. e.g., to filter a dataset so that only items selected interactively and that have a weight of more than 30:

transform
    << filter (fCompose (and (selected "brush") (expr "datum.weight > 30")))

Name a selection that is used as part of a conditional encoding.

color
    [ mSelectionCondition (selectionName "myBrush")
        [ mName "myField", mMType Nominal ]
        [ mStr "grey" ]
    ]

Global Configuration

Configuration options that affect the entire visualization. These are in addition to the data and transform options described above. See the Vega-Lite top-level spec documentation

name : String -> ( VLProperty, Spec )

Name to be associated with a visualization.

title : String -> ( VLProperty, Spec )

Title to be displayed in the visualization.

description : String -> ( VLProperty, Spec )

Description to be associated with a visualization.

height : Float -> ( VLProperty, Spec )

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

width : Float -> ( VLProperty, Spec )

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

padding : Padding -> ( VLProperty, Spec )

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

paSize : Float -> Padding

Indicate uniform padding around a visualization in pixel units.

paEdges : Float -> Float -> Float -> Float -> Padding

Padding around a visualization in pixel units. The four parameters refer to left, top, right, and bottom edges respectively.

autosize : List Autosize -> ( VLProperty, Spec )

Declare the way the view is sized. See the Vega-Lite autosize documentation.

enc = ...
toVegaLite
    [ width 250
    , height 300
    , autosize [ asFit, asPadding, asResize ]
    , dataFromUrl "data/population.json" []
    , bar []
    , enc []
    ]

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).

No autosizing to be applied.

Automatically expand size of visualization from the given dimensions in order to fit in all supplementary 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.

background : String -> ( VLProperty, Spec )

Background color of the entire visualization. For view compositions, single views or layers can have their own background styles in addition to this global background color. Should be specified with a CSS string such as #ffe or rgb(200,20,150). If not specified the background will be transparent.

View Background

The background of a single view in a view composition can be styled independently of other views. For more details see the Vega-Lite view background documentation

The background style of a single view or layer in a view composition.

viewStyle : List String -> ViewBackground

A list of named styles to apply to a single view background. A named style can be specified via coNamedStyle or coNamedStyles if more than one style is required. Later styles in the list will override earlier styles if there is a conflict in any of the mark properties specified.

The radius in pixels of rounded corners in single view or layer background.

viewFill : Maybe String -> ViewBackground

Fill color for a single view or layer background.

Fill opacity for a single view or layer background.

Overall opacity for a single view or layer background.

viewStroke : Maybe String -> ViewBackground

Stroke color for line around a single view or layer background. If Nothing is provided, no strokes are drawn around the view.

Stroke cap line-ending around a single view or layer background.

Stroke dash style for a line around a single view or layer background.

Stroke dash offset for line around a single view or layer background.

Stroke line-joining style around a single view or layer background.

Stroke mitre limit at which to bevel a line join around a single view or layer background.

Stroke opacity around a single view or layer background.

Stroke around a single view or layer background.

Style Setting

Allows default properties for most marks and guides to be set. See the Vega-Lite configuration documentation.

configure : List LabelledSpec -> ( VLProperty, Spec )

Create a single global configuration from a list of configuration specifications. See the Vega-Lite documentation.

config =
    configure
        << configuration (coAxis [ axcoDomainWidth 1 ])
        << configuration (coView [ vicoStroke Nothing ])
        << configuration (coSelection [ ( seSingle, [ seOn "dblclick" ] ) ])
configuration : ConfigurationProperty -> List LabelledSpec -> List LabelledSpec

A configuration option to be applied globally across the visualization.

Configure the default appearance of area marks.

Configure the default sizing of visualizations.

Configure the default appearance of axes.

Configure the default appearance of x-axes.

Configure the default appearance of y-axes.

Configure the default appearance of left-side axes.

Configure the default appearance of right-side axes.

Configure the default appearance of top-side axes.

Configure the default appearance of bottom-side axes.

Configure the default appearance of axes with band scaling.

Configure the default background color of visualizations.

Configure the default appearance of bar marks.

Configure the default appearance of circle marks.

Configure the default title style for count fields.

Configure the default title generation style for fields.

Configure the default appearance of geoshape marks.

Configure the default appearance of facet layouts.

Configure the default appearance of facet headers.

Configure the default appearance of legends.

Configure the default appearance of line marks.

Configure the default mark appearance.

Configure the default appearance of a single named style.

Configure the default appearance of a list of named styles.

Configure the default number formatting for axis and text labels.

Configure the default padding in pixels from the edge of the of visualization to the data rectangle.

Configure the default appearance of point marks.

Configure the default style of map projections.

Configure the default range properties used when scaling.

Configure the default appearance of rectangle marks.

Configure the default handling of invalid (null and NaN) values. If true, invalid values are skipped or filtered out when represented as marks.

Configure the default appearance of rule marks.

Configure the default scale properties used when scaling.

Configure the default appearance of selection marks.

Configure the default appearance of square marks.)

Configure the default stack offset style for stackable marks.

Configure the default appearance of text marks.

Configure the default appearance of tick marks.

Configure the default style of visualization titles.

Configure the default time format for axis and legend labels.

coTrail : List MarkProperty -> List LabelledSpec -> List LabelledSpec

Configure the default style of trail marks.

Configure the default single view style.

Axis Configuration Options

See the Vega-Lite axis config documentation.

Default axis band position.

Whether or not an axis domain should be displayed by default.

Default axis domain color.

Default axis domain opacity.

Default axis domain width style.

Default maximum extent style.

Default minimum extent style.

Whether or not an axis grid is displayed by default.

Default axis grid color style.

axcoGridDash : List Float -> AxisConfig

Default axis line dash style.

Default axis grid line opacity.

Default axis grid line width.

Whether or not an axis has labels by default.

Default axis label horizontal alignment.

Default axis label angle.

Default axis label vertical alignment.

axcoLabelBound : Maybe Float -> AxisConfig

Default axis label bounding when label exceeds available space. If Nothing, no check for label size is made. A number specifies the permitted overflow in pixels.

Default axis label color.

axcoLabelFlush : Maybe Float -> AxisConfig

Default label alignment at beginning or end of the axis. Specifies the distance threshold from an end-point within which labels are flush-adjusted or if Nothing, no flush-adjustment made.

Defailt number of pixels by which to offset flush-adjusted labels.

Default axis label font weight.

Default axis label font.

Default axis label font size.

Default axis label limit (how much a label can extend beyond the left/bottom or right/top of the axis line).

Default axis label opacity.

Default axis label overlap strategy for cases where labels cannot fit within the allotted space.

Default axis label padding (space between labels in pixels).

Whether or not an axis should use short time labels by default.

Whether or not an axis should show ticks by default.

Default axis tick mark color.

Whether or not by default an extra axis tick should be added for the initial position of axes.

Default offset in pixels of axis ticks, labels and gridlines.

Default opacity of axis ticks.

Whether or not axis tick labels use rounded values by default.

Default axis tick mark size.

The minimum desired step between axis ticks, in terms of scale domain values. For example, a value of 1 indicates that ticks should not be less than 1 unit apart. If specified, the tick count` value will be adjusted, if necessary, to enforce the minimum step value.

Deprecated in favour of axcoTickMinStep.

Default axis tick mark width.

Default axis tick label horizontal alignment.

Default axis title angle.

Default axis title vertical alignment.

Default axis title color.

Default axis title font.

Default axis title font weight.

Default axis title font size.

Default axis title maximum size.

Default opacity of axis titles.

Default axis title padding between axis line and text.

Default axis x-position relative to the axis group.

Default axis y-position relative to the axis group.

Legend Configuration Options

See the Vega-Lite legend configuration documentation.

Default maximum height of legend entries.

Default horizontal padding between symbol legend entries.

Default number of columns in which to arrange symbol legend entries.

Default legend corner radius.

Default background legend color.

Default legend position relative to the main plot content.

Default offset in pixel units between the legend and the enclosing group or data rectangle.

Default legend border color.

Default legend border stroke dash style.

Default legend border stroke width.

Default spacing in pixel units between a legend and axis.

Default vertical spacing in pixel units between legend symbol entries.

Default direction of a color ramp legend.

Default vertical alignment for labels in a color ramp legend.

Default maximum allowable length for labels in a color ramp legend.

Default vertical offset in pixel units for labels in a color ramp legend.

Default color for strokes in a color ramp legend.

Default width for strokes in a color ramp legend.

Default height of a color ramp legend.

Default width of a color ramp legend.

Defailt alignment to apply to symbol legends rows and columns.

Default horizontal alignment of legend labels.

Default vertical alignment of legend labels.

Default color for legend labels.

Default font for legend labels.

Default font size legend labels.

Default maximum width for legend labels in pixel units.

Default offset for legend labels.

Strategy for resolving overlapping legend labels.

Whether or not time labels are abbreviated by default in a legend.

Default spacing between legend items.

Default legend symbol fill color for when no fill scale color in legend encoding.

Default legend symbol stroke color for when no stroke scale color in legend encoding.

Default direction of a symbol legend.

Default legend symbol fill color.

Default horizontal pixel offset for legend symbols.

Default legend symbol size.

Default legend symbol outline color.

Default legend symbol stroke width.

Default legend symbol type.

Default horizontal alignment for legend titles.

Default vertical alignment for legend titles.

Default color legend titles.

Default font for legend titles.

Default font size for legend titles.

Default font weight for legend titles.

Default maximum size in pixel units for legend titles.

Default spacing in pixel units between title and legend.

Scale Configuration Options

See the Vega-Lite scale configuration documentation

Default inner padding for x and y band-ordinal scales.

Default outer padding for x and y band-ordinal scales.

Default inner padding for x and y band-ordinal scales of bar marks.

Default outer padding for x and y band-ordinal scales of bar marks.

Default inner padding for x and y band-ordinal scales of rect marks.

Default outer padding for x and y band-ordinal scales of rect marks.

Whether or not by default values that exceed the data domain are clamped to the min/max range value.

Default maximum value for mapping quantitative fields to a bar's size/bandSize.

Default minimum value for mapping quantitative fields to a bar's size/bandSize.

Default maximum value for mapping a quantitative field to a text mark's size.

Default minimum value for mapping a quantitative field to a text mark's size.

Default maximum opacity (in the range [0, 1]) for mapping a field to opacity.

Default minimum opacity (0 to 1) for mapping a field to opacity.

Default maximum size for point-based scales.

Default minimum size for point-based scales (when not forced to start at zero).

Default maximum stroke width for rule, line and trail marks.

Default minimum stroke width for rule, line and trail marks.

Default padding for point-ordinal scales.

sacoRangeStep : Maybe Float -> ScaleConfig

Default range step for band and point scales when the mark is not text.

Whether or not numeric values are rounded to integers when scaling. Useful for snapping to the pixel grid.

Default range step for x band and point scales of text marks.

Whether or not to use the source data range before aggregation.

Scale Range Configuration Options

See the Vega-Lite scheme configuration documentation.

Default color scheme for categorical ranges.

Default diverging color scheme.

Default 'heatmap' color scheme.

Default ordinal color scheme.

racoRamp : String -> RangeConfig

Default ramp (continuous) color scheme.

Default color scheme symbols.

Title Configuration Options

See the Vega-Lite title configuration documentation

Default anchor position when placing titles.

Default angle when orientating titles.

Default vertical alignment when placing titles.

Default color when showing titles.

ticoFont : String -> TitleConfig

Default font when showing titles.

Default font size when showing titles.

Default font weight when showing titles.

Default maximum length in pixel units when showing titles.

Default offset in pixel units of titles relative to the chart body.

Default placement of titles relative to the chart body.

View Configuration Options

See the Vega-Lite view configuration documentation

Default width of single views (e.g. each view in a trellis plot).

Default height of single views (e.g. each view in a trellis plot).

Whether or not by default single views should be clipped.

The radius in pixels of rounded rectangle corners.

vicoFill : Maybe String -> ViewConfig

Default fill color for single views.

Default fill opacity for single views.

Default overall opacity for single views.

vicoStroke : Maybe String -> ViewConfig

Default stroke color for single views. If Nothing is provided, no strokes are drawn around the view.

Default stroke cap line-ending style for single views.

vicoStrokeDash : List Float -> ViewConfig

Default stroke dash style for single views.

Default stroke dash offset for single views.

Default stroke line-joining style for single views.

Default stroke mitre limit at which to bevel a line join in single views.

Default stroke opacity for single views.

Default stroke width of single views.

Anchor some text at its start.

Anchor some text in its start.

Anchor some text at its end.

Field titles to be displayed fully as 'Sum of field', 'Year of date' etc.

Field titles to be displayed as 'SUM(field)', 'YEAR(date)' etc.

Field titles to be displayed simply by their name without additional text.

Facet Configuration Options

See the Vega-Lite facet config documentation.

Configuration option for the maximum number of columns to use in a faceted flow layout.

Configuration option for the spacing in pixels between sub-views in a view composition, such as a faceted or concatenated view.

General Data functions

In addition to more general data types like integers and string, the following types can carry data used in specifications.

boo : Bool -> DataValue

A Boolean data value.

A true value used for functions that can accept a Boolean literal or a reference to something that generates a Boolean value. Convenience function equivalent to boo True

A false value used for functions that can accept a Boolean literal or a reference to something that generates a Boolean value. Convenience function equivalent to boo False

Date-time data value.

num : Float -> DataValue

A numeric data value.

str : String -> DataValue

A string data value.

boos : List Bool -> DataValues

A list of Boolean data values.

dts : List (List DateTime) -> DataValues

List of date-time data values.

nums : List Float -> DataValues

List of numeric data values.

strs : List String -> DataValues

A list of string data values.

dtYear : Int -> DateTime

A year.

Year quarter (1 to 4).

Month of a year (1 to 12).

dtDate : Int -> DateTime

Day of the month (1 to 31).

Day of the week.

dtHour : Int -> DateTime

Hour of the day (0=midnight, 1=1am, 23=11pm etc.).

Minute of an hour (0-59).

Second of a minute (0-59).

Millisecond of a second (0-999).

= Jan
| Feb
| Mar
| Apr
| May
| Jun
| Jul
| Aug
| Sep
| Oct
| Nov
| Dec

Identify a month of the year.

type DayName
= Mon
| Tue
| Wed
| Thu
| Fri
| Sat
| Sun

Day of the week.

Day of the month (1-31) time unit used for discretizing temporal data.

Day of the week time unit used for discretizing temporal data.

Hour of the day time unit used for discretizing temporal data.

Hours and minutes time unit used for discretizing temporal data.

Hours, minutes and seconds time unit used for discretizing temporal data.

Milliseconds time unit used for discretizing temporal data.

Minute of the hour time unit used for discretizing temporal data.

Minutes and seconds time unit used for discretizing temporal data.

Month of the year (1-12) time unit used for discretizing temporal data.

Month and day of month time unit used for discretizing temporal data.

Month, day of month and hour of day time unit used for discretizing temporal data.

Year quarter time unit used for discretizing temporal data.

Year quarter and month time unit used for discretizing temporal data.

Second of a minute time unit used for discretizing temporal data.

Seconds and milliseconds time unit used for discretizing temporal data.

Year time unit used for discretizing temporal data.

Year and year quarter time unit used for discretizing temporal data.

Year, quarter and month time unit used for discretizing temporal data.

Year and month time unit used for discretizing temporal data.

Year, month and day of month time unit used for discretizing temporal data.

Year, month, day of month and hour of day time unit used for discretizing temporal data.

Time unit used for discretizing temporal data.

Time unit used for discretizing temporal data.

UTC version of a given a time (coordinated universal time, independent of local time zones or daylight saving). To encode a time as UTC (coordinated universal time, independent of local time zones or daylight saving), just use this function to convert another TimeUnit generating function. For example,

encoding
    << position X [ pName "date", pMType Temporal, pTimeUnit (utc yearMonthDateHours) ]

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 and anEnd.

Generated by arFlow, arColumn and arRow.

Generated by functions prefixed with ax, for example axBandPosition.

Generated by functions prefixed with axco.

Generated by expr, selected, selectionName, and, or and not.

type Bounds

Generated by boFull and boFlush.

type Channel

Generated by chX, chY, chX2, chY2, chColor, chOpacity, chShape and chSize.

Generated by noClip and clipRect.

Generated by caNone, caEach and caAll.

type Cursor

Generated by functions that start with cu.

Generated by foBoo, foNum, foDate and foUtc.

Generated by boo, true, false, dt, num and str.

Generated by boos, dts, nums and strs.

Generated by facoColumns and facoSpacing.

Generated by columnBy and rowBy.

Generated by numRange and dtRange.

type HAlign

Generated by haLeft, haCenter and haRight.

The imputation method to use when replacing values.

type Legend

Generated by leGradient and leSymbol.

Generated by functions prefixed with leco.

Generated by functions prefixed with le. For example leCornerRadius.

Generated by leNums, leStrs and leDts.

Appearance of a line marker that is overlaid on an area mark. generated by lmMarker and lmNone.

= ONone
| OParity
| OGreedy

Generated by osNone, osGreedy and osParity.

type Padding

Generated by paSize and paEdges.

Generated by pmNone, pmTransparent and pmMarker.

Generated by functions prefixed with raco.

Generated by rowFields and columnFields.

Generated by reShared and reIndependent.

type Resolve

Generated by reAxis, reLegend and reScale.

Generated by functions prefixed by saco

Generated by raNums, raStrs and raName.

Generated by seInterval, seSingle and seMulti.

type Side

Generated by siLeft, siRight, siTop, and siBottom

Generated by stZero, stCenter, stNormalize and stNone.

Generated by stOffset and stSort.

Generated by caButt, caRound and caSquare.

Generated by joMiter, joRound and joBevel.

Generated by functions prefixed by tico.

Generated by ttEncoding, ttData and ttNone.

type VAlign

Generated by vaTop, vaMiddle and vaBottom.

Generated by functions prefixed with vico.

type Window

Generated by wiAggregateOp, wiOp, wiParam and wiField.