gicentre/elm-vegalite/5.3.0

NOTE: the latest version is 5.8.0

VegaLite

Create Vega-Lite visualization specifications in Elm. This package allows you to generate the JSON specs that may be passed to the Vega-Lite runtime library via a port to activate the visualization. Alternatively, to avoid coding the link to the Vega-Lite runtime, you can embed specifications directly in a litvis document.

  1. Creating a Specification
  2. Specifying the Data to Visualize
  3. Transforming Data
  4. Specifying Marks
  5. Encoding Data as Channels
  6. View Composition
  7. Parameters
  8. Top-level Settings
  9. General Data Functions
  10. Type Reference

1. 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 functions such as encodings with 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:

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


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

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 geoshape, point and line.

Mark functions specify the graphical 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, hyperlink and order.

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

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

Supplementary and configuration properties provide a means to add metadata and styling to one or more visualizations. Generated by name, title, description, background, backgroundExpr, width, height, widthStep, heightStep, 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 full visualization specification.

You only need to name something as a Spec when providing a top level function with a type signature. For example,

myBarchart : Spec
myBarchart =
    ...
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

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

myCharts : Spec
myCharts =
    combineSpecs
        [ ( "vis1", myVis1 )
        , ( "vis2", myVis2 )
        , ( "vis3", myVis3 )
        ]

2. Specifying the Data to Visualize

To create a visualization, you will need to specify what data you wish to visualize. For context, see the Vega-Lite documentation.

dataFromUrl : String -> List Format -> Data

Declare a data source from a url. The URL can be a local path such as a file name in the same folder as the elm specification 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.

myPopData : Data
myPopData =
    dataFromUrl "https://vega.github.io/vega-lite/data/population.json" []


myBikeData : Data
myBikeData =
    dataFromUrl "./data/bicycleHires.csv"
        [ parse
            [ ( "numHires", foNum )
            , ( "avHireTime", foNum )
            ]
        ]
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, so beware of inadvertently removing data rows at the 'bottom' of a table.

A list of field formatting instructions can be provided as the first parameter or an empty list to use the default formatting. Simple numbers and strings do not normally need formatting, but it is good practice to explicitly declare date-time formats because default date-time formats can vary between browsers.

The columns are most easily generated with dataColumn:

myChart : Spec
myChart =
    let
        data =
            dataFromColumns [ parse [ ( "Year", foDate "%Y" ) ] ]
                << dataColumn "Animal" (strs [ "Fish", "Dog", "Cat" ])
                << dataColumn "Age" (nums [ 28, 12, 6 ])
                << dataColumn "Year" (strs [ "2015", "2019", "2020" ])
    in
    toVegaLite [ data [], ... ]

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

dataColumn : String -> DataValues -> List DataColumn -> List DataColumn

Create a column of data. A column has a name and a list of values which is then added to an existing list of data columns. This allows multiple data column specifications to be chained together with the << operator. For example, to represent a table of data in this form:

| x   | y   |
| --- | --- |
| a   | 1   |
| b   | 2   |
| c   | 3   |

you could specify:

myChart : Spec
myChart =
    let
        data =
            dataFromColumns []
                << dataColumn "x" (strs [ "a", "b", "c" ])
                << dataColumn "y" (nums [ 1, 2, 3 ])
    in
    toVegaLite [ data [], ... ]
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.

myChart : Spec
myChart =
    let
        data =
            dataFromRows [ parse [ ( "Year", foDate "%Y" ) ] ]
                << dataRow [ ( "Animal", str "Fish" ), ( "Age", num 28 ), ( "Year", str "2015" ) ]
                << dataRow [ ( "Animal", str "Dog" ), ( "Age", num 12 ), ( "Year", str "2019" ) ]
                << dataRow [ ( "Animal", str "Cat" ), ( "Age", num 6 ), ( "Year", str "2020" ) ]
    in
    toVegaLite [ data [], ... ]

Generally, adding data by column is more efficient and less error-prone, but occasionally there can be greater clarity in arranging data by rows. For more complex inline data tables, such as mixtures of arrays and objects, consider using dataFromJson.

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

Create a row of data. A row comprises a list of (columnName, value) pairs. For example, to specify this table:

| x   | y   |
| --- | --- |
| a   | 1   |
| b   | 2   |
| c   | 3   |




myChart : Spec
myChart =
    let
        data =
            dataFromRows []
                << dataRow [ ( "x", str "a" ), ( "y", num 1 ) ]
                << dataRow [ ( "x", str "b" ), ( "y", num 2 ) ]
                << dataRow [ ( "x", str "c" ), ( "y", num 3 ) ]
    in
    toVegaLite [ data [], ...]
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.

myChart : Spec
myChart =
    let
        geojson =
            geometry (geoPolygon [ [ ( -3, 59 ), ( 4, 59 ), ( 4, 52 ), ( -3, 59 ) ] ]) []
    in
    toVegaLite [ dataFromJson geojson [], geoshape [] ]

For more general cases of json creation such as data tables that mix arrays and objects, consider combining with jsonToSpec. For example,

myChart : Spec
myChart =
    let
        data =
            jsonToSpec """{
            "Revenue" : [ 150, 225, 300 ],
            "Profit" : [ 20, 25, 30 ],
            "Order size" : [ 350, 500, 600 ],
            "New customers" : [ 1400, 2000, 2500 ],
            "Satisfaction" : [ 3.5, 4.25, 5 ]
        }"""
                |> dataFromJson
    in
    toVegaLite [ data [], ... ]
jsonToSpec : String -> Spec

Convert a string representing some JSON into a Spec. Useful when combined with dataFromJson to compactly import inline JSON as data. For example,

myChart : Spec
myChart =
    let
        data =
            jsonToSpec """{
            "Revenue" : [ 150, 225, 300 ],
            "Profit" : [ 20, 25, 30 ],
            "Order size" : [ 350, 500, 600 ],
            "New customers" : [ 1400, 2000, 2500 ],
            "Satisfaction" : [ 3.5, 4.25, 5 ]
        }"""
                |> dataFromJson
    in
    toVegaLite [ data [], ... ]

This can also be used to store a full visualization specification from a JSON object. For example,

myChart : Spec
myChart =
    """
{
    "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
    "data": { "url": "https://cdn.jsdelivr.net/npm/[email protected]/data/cars.json"},
    "mark": "bar",
    "encoding": {
        "x": { "field": "Origin" },
        "y": { "field": "Miles_per_Gallon", "aggregate": "mean" }
    }
}
""" |> jsonToSpec

But note this is not type-safe – if the JSON is not well-formed, a JSON null value is returned.

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.

myChart : Spec
myChart =
    let
        data =
            dataFromColumns []
                << dataColumn "name" (strs [ "alphaville", "betatown" ])
                << dataColumn "pop" (nums [ 9350, 4770 ])


        geoBounds =
            geometry (geoPoints [ ( -4, 55 ), ( 3, 59 ) ]) []
                |> dataFromJson
    in
    toVegaLite
        [ datasets
            [ ( "myData", data [] )
            , ( "myJson", geoBounds [] )
            ]
        , dataFromSource "myData" []
        , ...
        ]
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.

myChart : Spec
myChart =
    let
        data = ...
        json = ...
    in
    toVegaLite
        [ datasets [ ( "myData", data ), ( "myJson", dataFromJson json [] ) ]
        , dataFromSource "myData" []
        , ...
        ]
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.

myChart : Spec
myChart =
    let
        data =
            dataFromUrl "myData.json" []
                |> dataName "myName"
    in
    toVegaLite [ data , ...]
noData : Data

Ignore the data of a specification's parent when used in a composed spec such as layering or concatenation.

type alias Data =
( VLProperty, Spec )

Type annotation for describing data generation functions. Useful when annotating top-level data-generating functions. For example,

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

Type annotation for a single column of data. Used when describing inline data with dataColumn.

type alias DataRow =
Spec

Type annotation for a single row of data. Used when describing inline data with dataRow.

2.1 Geographic Data

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

Specify a geometric object. The first parameter is the geometry type, the second an optional list of properties to be associated with the object.

myGeo : Data
myGeo =
    (geometry (geoPoints [ ( -4, 55 ), ( 3, 59 ) ]) []
        |> dataFromJson
    )
        []
geoFeatureCollection : List Spec -> Spec

A collection of geo features to be used in a geoshape specification. Each feature in this collection can be created with geometry.

myGeo : Data
myGeo =
    (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" ) ]
        ]
        |> dataFromJson
    )
        []
geometryCollection : List Spec -> Spec

Collection of geometry objects that make up a single feature. Can be used in a geoshape specification. Each geometry object can be created with geometry.

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

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

myGeo : Data
myGeo =
    (geometry (geoPoint -3.5 55.5) []
        |> dataFromJson
    )
        []
geoPoints : List ( Float, Float ) -> Geometry

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

myGeo : Data
myGeo =
    (geometry (geoPoints [ ( -4, 55 ), ( -3, 59 ), ( -3, 56 ) ]) []
        |> dataFromJson
    )
        []
geoLine : List ( Float, Float ) -> Geometry

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

myGeo : Data
myGeo =
    (geometry (geoLine [ ( -3, 59 ), ( 4, 59 ), ( 4, 52 ) ]) []
        |> dataFromJson
    )
        []
geoLines : List (List ( Float, Float )) -> Geometry

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

myGeo : Data
myGeo =
    (geometry
        (geoLines
            [ [ ( -3, 59 ), ( 4, 59 ), ( 4, 52 ) ]
            , [ ( -4, 57 ), ( 2, 57 ), ( 2, 56 ) ]
            ]
        )
        []
        |> dataFromJson
    )
        []
geoPolygon : List (List ( Float, Float )) -> Geometry

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

myGeo : Data
myGeo =
    (geometry (geoPolygon [ [ ( -3, 59 ), ( 4, 59 ), ( 4, 52 ), ( -3, 59 ) ] ]) []
        |> dataFromJson
    )
        []
geoPolygons : List (List (List ( Float, Float ))) -> Geometry

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

myGeo : Data
myGeo =
    (geometry
        (geoPolygons
            [ [ [ ( -3, 59 ), ( 4, 59 ), ( 4, 52 ), ( -3, 59 ) ] ]
            , [ [ ( -4, 57 ), ( 2, 57 ), ( 2, 56 ), ( -4, 57 ) ] ]
            ]
        )
        []
        |> dataFromJson
    )
        []

2.2 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 when referring to it within a specification. For example,

sineWave : Spec
sineWave =
    let
        myData =
            dataSequence 0 (2 * pi) (pi / 90)


        trans =
            transform
                << calculateAs "sin(datum.data)" "y"


        enc =
            encoding
                << position X [ pName "data", pQuant ]
                << position Y [ pName "y", pQuant ]
    in
    toVegaLite [ myData, trans [], enc [], line [] ]

To give the sequence 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.

myData : Data
myData =
    dataSequenceAs 0 (2 * pi) (pi / 90) "x"
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.

myGlobe : Spec
myGlobe =
    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.

myGlobe : Spec
myGlobe =
    let
        proj =
            projection [ prType orthographic ]


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


        gratSpec =
            asSpec
                [ graticule [ grStep ( 15, 15 ) ]
                , geoshape [ maFilled False ]
                ]
    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. While major graticule lines extend to both poles, by default 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.

2.3 Formatting Input Data

See the Vega-Lite format and JSON documentation.

parse : List ( String, DataType ) -> Format

Specify parsing rules when processing some data text with dataFromUrl, dataFromColumns etc. The parameter should be a list of tuples in the form (fieldName, DataType). Useful when automatic type inference needs to be overridden, for example to ensure numbers with - symbols are treated as integers and not strings in transform calculations or when converting integers representing years into dates. For example,

myData : Data
myData =
    dataFromUrl "myDataFile.csv"
        [ parse
            [ ( "year", foDate "%Y" )
            , ( "change", 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

Specify a date/time format when parsing input data. Should use D3's formatting specifiers to describe the data-time format or an empty string for default formatting. For example,

myData : Data
myData =
    dataFromUrl "myDataFile.csv"
        [ parse [ ( "timestamp", foDate "%d %b %Y %H:%M" ) ] ]
foUtc : String -> DataType

Similar to foDate but for UTC format dates.

Specify a CSV (comma-separated values) file format when reading a data file. Only necessary if the file extension does not indicate the type. For example,

myData : Data
myData =
    dataFromUrl "myData" [ csv ]

Specify a TSV (tab-separated values) file format when reading a data file. Only necessary if the file extension does not indicate the type. For example,

myData : Data
myData =
    dataFromUrl "myData" [ tsv ]
dsv : Char -> Format

Specify a custom delimited file format (DSV) with a given separator when reading a data file.

myData : Data
myData =
    dataFromUrl "myData" [ dsv '|' ]

Specify an Apache arrow data file format when reading a data file. For example,

myData : Data
myData =
    dataFromUrl "https://gicentre.github.io/data/scrabble.arrow" [ arrow ]

A topoJSON feature format containing an object with the given name. The name of the object can be found by inspecting the topoJSON file and searching for the value associated with the objects key.

myData : Data
myData =
    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. Generally meshes can be faster to render but only suitable for showing boundary features, not filled areas. For example:

myLondon : Spec
myLondon =
    toVegaLite
        [ dataFromUrl "https://gicentre.github.io/data/geoTutorials/londonBoroughs.json"
            [ topojsonMesh "boroughs" ]
        , geoshape [ maFilled False ]
        ]
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.


3. Transforming Data

Transformation rules are applied to data fields or geospatial coordinates before they are encoded visually. They are used when data need to be changed in some way, such as filtering items, calculating new fields, joining data tables or performing statistical analysis.

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"

3.1 Map Projections

See the Vega-Lite map projection documentation.

Create a map projection to transform geospatial coordinates. Only data positioned with Longitude and Latitude or displayed as a geoshape are affected by a projection.

myMap : Spec
myMap =
    let
        myData =
            dataFromUrl "https://gicentre.github.io/data/geoTutorials/londonBoroughs.json"
                [ topojsonFeature "boroughs" ]


        proj =
            projection
                [ prType transverseMercator
                , prRotate 2 0 0
                ]
    in
    toVegaLite [ myData, proj, geoshape [] ]

Provide an expression to a map projection property function requiring a numeric value. This can be used for interactive parameterisation when an expression is bound to an input element. For example,

myMap : Spec
myMap =
    let
        geoData =
            dataFromUrl "https://gicentre.github.io/data/geoTutorials/world-110m.json"
                [ topojsonFeature "countries1" ]


        ps =
            params
                << param "zoom"
                    [ paValue (num 40)
                    , paBind (ipRange [ inMin 40, inMax 500 ])
                    ]


        proj =
            projection [ prNumExpr "zoom" prScale ]
    in
    toVegaLite [ ps [], geoData, proj, geoshape [] ]

Type of global map projection. For example,

myProj =
    projection [ prType orthographic ]

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 (shape-preserving) conic map projection.

An equal area conic map projection.

An equidistant conic map projection. Distance is preserved along a standard parallel (or two parallels for secant projections).

An Equal Earth map projection that provides a reasonable shape approximation while retaining relative areas.

An equirectangular map projection that maps longitude to x and latitude to y. While showing less area distortion towards the poles than the 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.

A natural earth map projection.

An orthographic map projection.

A stereographic map projection.

A transverse Mercator map projection.

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

prExpr : String -> Projection

Specify a map projection type with an expression that evaluates to a valid projection name. Useful for interactive selection of map projection. For example,

myMap : Spec
myMap =
    let
        geoData =
            dataFromUrl "https://gicentre.github.io/data/geoTutorials/world-110m.json"
                [ topojsonFeature "countries1" ]


        ps =
            params
                << param "myProj"
                    [ paValue (str "EqualEarth")
                    , paBind
                        (ipSelect
                            [ inName "Map projection "
                            , inOptions
                                [ "EqualEarth"
                                , "Orthographic"
                                ]
                            ]
                        )
                    ]


        proj =
            projection [ prType (prExpr "myProj") ]
    in
    toVegaLite [ ps [], geoData, proj, geoshape [] ]

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

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

Indicate no clipping to be applied.

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

Specify the bounds in pixel coordinates of a clipped map projection in left, top, right, and bottom order. For example,

myMap : Spec
myMap =
    let
        geoData =
            dataFromUrl "https://gicentre.github.io/data/geoTutorials/world-110m.json"
                [ topojsonFeature "countries1" ]


        proj =
            projection
                [ clipRect 0 0 600 270
                    |> prClipExtent
                ]
    in
    toVegaLite
        [ width 600
        , height 300
        , geoData
        , proj
        , geoshape []
        ]
clipRectExpr : String -> String -> String -> String -> ClipRect

Specify the bounds of a clipped map projection region with four expressions in left, top, right, and bottom order that evaluate to pixel positions. Useful when parameterising clip extent interactively. For example,

myMap : Spec
myMap =
    let
        geoData =
            dataFromUrl "https://gicentre.github.io/data/geoTutorials/world-110m.json"
                [ topojsonFeature "countries1" ]


        ps =
            params
                << param "left"
                    [ paValue (num 0)
                    , paBind (ipRange [ inMin 0, inMax 300 ])
                    ]
                << param "right"
                    [ paValue (num 600)
                    , paBind (ipRange [ inMin 300, inMax 600 ])
                    ]
                << param "top"
                    [ paValue (num 0)
                    , paBind (ipRange [ inMin 0, inMax 150 ])
                    ]
                << param "bottom"
                    [ paValue (num 300)
                    , paBind (ipRange [ inMin 150, inMax 300 ])
                    ]


        proj =
            projection
                [ clipRectExpr "left" "top" "right" "bottom"
                    |> prClipExtent
                ]
    in
    toVegaLite
        [ width 600
        , height 300
        , ps []
        , geoData
        , proj
        , geoshape []
        ]

Adjust map projection to fit the given geoShape within the display area. The geoShape can be a feature collection, a single feature or array of features. This is usually easier than adjusting a projection's prScale and prTranslate. For example,

geoFrame =
    geometry (geoPoints [ ( -8, 60 ), ( 1, 47 ) ])
        []


proj =
    projection [ prFit geoFrame ]
prCenter : Float -> Float -> ProjectionProperty

Projection’s center as longitude and latitude in degrees.

prCenterExpr : String -> String -> ProjectionProperty

Specify a projection’s centre with two expressions that should evaluate to a longitude and latitude respectively.

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 in pixel units, which if set, override automatic positioning of a geo feature to fit within the viewing area. Parameters should be provided in x y order.

prTranslateExpr : String -> String -> ProjectionProperty

Specify a projection’s panning translation in pixel units, with two expressions that should evaluate to x and y translations respectively.

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.

prRotateExpr : String -> String -> String -> ProjectionProperty

Specify a projection’s three-axis rotation angle with three expressions that should evaluate to angular rotations (degrees) in lambda phi gamma order.

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

Standard parallel for map projections such as the 'Armadillo'.

prParallels : Float -> Float -> ProjectionProperty

A conic projection’s two standard parallels.

prParallelsExpr : String -> String -> ProjectionProperty

Specify a conic projection’s two standard parallels with two expressions.

Radius in pixels when drawing geo point features in a GeoFeature.

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

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

'Satellite' map projection tilt.

3.2 Aggregation

See the Vega-Lite aggregate documentation.

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 join aggregate 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 opCount, 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.

opArgMax : Maybe String -> Operation

An input data object containing the minimum field value to be used in an aggregation operation. If supplied as part of an encoding aggregation, the parameter should be Just the name of the field to maximise. For example, the following would find the production budget for the maximum US grossing film in each genre:

encoding
    << position X
        [ pName "Production_Budget"
        , pQuant
        , pAggregate (opArgMax (Just "US_Gross"))
        ]
    << position Y [ pName "Major_Genre", pNominal ]

If supplied as part of a transform, the parameter should be Nothing as the field is specified in the aggregate parameter.

trans =
    transform
        << aggregate
            [ opAs (opArgMax Nothing) "US_Gross" "amUSGross" ]
            [ "Major_Genre" ]
opArgMin : Maybe String -> 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.

Product of field values 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 first parameter is a list of customisation options (biBase, biDivide etc.) or an empty list to use the default binning. The second is the field to bin and the third the name to give the output binned data. Usually, direct binning within an encoding is preferred over this form of bin transformation.

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

The name given to store the binned values (third parameter) will reference the start of each bin value. To extract the end of each bin, use the same name but with _end appended.

Value in the binned domain at which to anchor the binning. Boundaries are possibly shifted to ensure they align with the anchor value.

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 extent of bin values when binning a collection of values. The first and second parameters indicate the minimum and maximum extent. To base a binning extent on an interactive selection, use biSelectionExtent instead.

Set the desired range of bin values based on an interactive selection. The parameter should be the name of an interval selection parameter that defines the extent.

ps =
    params
        << param "brush" [ paSelect seInterval [ seEncodings [ chX ] ] ]


enc =
    encoding
        << position X
            [ pName "temperature"
            , pBin [ biSelectionExtent "brush" ]
            ]

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.

3.4 Stacking

See the Vega-Lite stack documentation

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.

3.5 Data Calculation

See Vega-Lite calculate documentation.

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

Generate a new data field based on some calculations from existing values and 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"

3.6 Filtering

See the Vega-Lite filter documentation.

filter : Filter -> List LabelledSpec -> List LabelledSpec

Apply a filter to a channel or field that specifies which values will 'pass through' for encoding. A filter can an expression such as,

trans =
    transform << filter (fiExpr "datum.y < 50")

noting that to refer to a particular data value, prefix the field name with datum.. Alternatively a boolean filtering function such as fiOneOf or fiLessThan can be supplied,

trans =
    transform << filter (fiLessThan "y" (num 50))
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.

fiSelection : String -> Filter

Filter a data stream in response to the value of a selection parameter. Useful for creating interactive filtering from a selection.

Similar to fiSelection except that an empty selection filters out all values.

Convert a filter into a BooleanOp so that it may be used as part of a more complex Boolean composition.

trans =
    transform
        << filter
            (fiCompose
                (and
                    (fiValid "IMDB_Rating" |> fiOp)
                    (fiValid "Rotten_Tomatoes_Rating" |> fiOp)
                )
            )

Combine a data transformation operation with a filter before converting into a Boolean operation. This can be useful when working with dates. For example, the following will aggregate a set of dates into years and filter only those years between 2010 and 2017 inclusive:

filter
    (fiRange "date" (dtRange [ dtYear 2010 ] [ dtYear 2017 ])
        |> fiOpTrans (mTimeUnit year)
        |> fiCompose
    )

Note the use of fiCompose to convert the Boolean operation back into a Filter.

Build up a filtering predicate through logical composition (and, or etc.). For example, to filter only items selected interactively and that represent ages over 65:

trans =
    transform
        << filter
            (fiCompose
                (and (selected "brush") (expr "datum.age > 65"))
            )
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.

filter (fiRange "date" (dtRange [ dtYear 2006 ] [ dtYear 2016 ]))
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.

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

3.8 Folding and Pivoting

Data tidying operations that reshape the rows and columns of a dataset. See the Vega-Lite fold and pivot documentation.

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 'gather' in the Tidy Elm package and the pivot_longer / gather operation in the R tidyverse . It is the inverse of pivot.

data =
    dataFromColumns []
        << dataColumn "city" (strs [ "Bristol", "Sheffield", "Glasgow" ])
        << dataColumn "temp2017" (nums [ 12, 11, 7 ])
        << dataColumn "temp2018" (nums [ 14, 13, 10 ])


trans =
    transform
        << fold [ "temp2017", "temp2018" ]


enc =
    encoding
        << position X [ pName "key", pNominal ]
        << position Y [ pName "city", pNominal ]
        << size [ mName "value", mQuant ]
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.

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

Perform a pivot operation on a table. Spreads a key-value pair of fields across multiple fields according to the data in the key field. The first two parameters are the key and value fields respectively. The third is a set of customisation options. This performs the same function as 'spread' in the Tidy Elm package and the pivot_wider / spread operation in the R tidyverse. It is the inverse of fold.

data =
    dataFromColumns []
        << dataColumn "city" (strs [ "Bristol", "Bristol", "Sheffield", "Sheffield", "Glasgow", "Glasgow" ])
        << dataColumn "temperature" (nums [ 12, 14, 11, 13, 7, 10 ])
        << dataColumn "year" (nums [ 2017, 2018, 2017, 2018, 2017, 2018 ])


trans =
    transform
        << pivot "year" "temperature" [ piGroupBy [ "city" ] ]


enc =
    encoding
        -- 2017 temperatures for the Bristol, Sheffield and Glasgow
        << position X [ pName "2017", pQuant ]
        << position Y [ pName "city", pNominal ]
piGroupBy : List String -> PivotProperty

The data fields to group by when pivoting. If not specified, a single group containing all data objects will be used.

Maximum number of fields to generate when pivoting. If 0 or unspecified, all fields are pivoted. The pivot names are sorted in ascending order before any limit is applied.

The aggregation to apply to grouped fields during a pivot.

3.9 Relational Joining

Create lookups between data tables in order to join values from multiple sources. See the Vega-Lite lookup documentation.

String
-> Data
-> 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.

For linking data with interactive selections, see lookupSelection.

A common use for lookup is to join geographic and attribute data sources. Below geodata is the primary data source containing borough boundaries and censusData the secondary data source containing attribute data. Both have common data field values identifying a borough (id and borough) that is used to join the data sources:

geoData =
    dataFromUrl "city.json" [ topojsonFeature "boroughs" ]


censusData =
    dataFromUrl "census.csv" []


trans =
    transform
        << lookup "id"
            (censusData [])
            "borough"
            (luFields [ "carOwnership", "numBedrooms" ])
lookupSelection : String -> String -> String -> List LabelledSpec -> List LabelledSpec

Attach the results of an interactive selection to a primary data source. The first three parameters are the field in the primary data source to look up; the name of the interactive selection parameter; and the name of the field in the selection to link with the primary data field. This is similar to lookup except that the data in a selection are used in place of the secondary data source.

  ps =
      params
          << param "mySel"
              [ paSelect sePoint [ seOn "mouseover", seEncodings [ chX ] ] ]


  trans =
      transform
          << lookupSelection "country" "mySel" "country"
luFields : List String -> LookupFields

Names of the fields to be returned from a secondary data source when performing a lookup transformation.

luFieldsWithDefault : List String -> String -> LookupFields

The same as luFields except with a second parameter providing the default value if the lookup fails.

luFieldsAs : List ( String, String ) -> LookupFields

Names of the fields and their aliases to be returned from a secondary data source when performing a lookup transformation. Each tuple should be a name of a field to return followed by the new name to give it. Unlike luAs this allows separate aliases to be given to each matched field.

luFieldsAsWithDefault : List ( String, String ) -> String -> LookupFields

The same as luFieldsAs except with a second parameter providing the default value if the lookup fails.

luAs : String -> LookupFields

Name to give the entire set of fields in a secondary data source when performing a lookup. To refer to individual fields via this name, use Javascript dot notation (or if the field contains spaces, use equivalent array index notation in single quotes such as o['my field']).

data =
    dataFromUrl "data/flights-airport.csv" []


trans =
    transform
        << lookup "origin"
            (dataFromUrl "data/airports.csv" [])
            "iata"
            (luAs "o")


enc =
    encoding
        << position Longitude [ pName "o.longitude", pQuant ]
        << position Latitude [ pName "o.latitude", pQuant ]
luAsWithDefault : String -> String -> LookupFields

The same as luAs except with a second parameter providing the default value if the lookup fails.

3.10 Data Imputation

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

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

Impute missing data values as a data transform. 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.

For example, to impute the missing value of b with the mean of existing b values, when a is 30 and its color group (c) is 1:

let
    data =
        dataFromColumns []
            << dataColumn "a" (nums [ 0, 0, 10, 10, 20, 20, 30 ])
            << dataColumn "b" (nums [ 28, 91, 43, 55, 81, 53, 19 ])
            << dataColumn "c" (nums [ 0, 1, 0, 1, 0, 1, 0 ])


    trans =
        transform
            << impute "b" "a" [ imMethod imMean, imGroupBy [ "c" ] ]


    enc =
        encoding
            << position X [ pName "a", pQuant ]
            << position Y [ pName "b", pQuant ]
            << color [ mName "c", mNominal ]
in
toVegaLite [ data [], trans [], enc [], line [] ]
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.

3.11 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. For example, to randomly sample 50 values from a sine curve:

data =
    dataSequenceAs 0 13 0.001 "x"


trans =
    transform
        << calculateAs "sin(datum.x)" "y"
        << sample 50

3.12 Density Estimation

See the Vega-Lite density documentation

String
-> List LabelledSpec
-> List LabelledSpec

Apply Kernel Density Estimation to a data stream to generate a new stream of samples of the estimated density. Useful for representing probability distributions and generating continuous distributions from discrete samples.

dnGroupBy : List String -> DensityProperty

The data fields to group by when estimating density. If not specified, a single group containing all data objects will be used.

Whether or not density estimates will be cumulative. If unspecified, non-cumulative estimates will be generated.

Whether density estimates should generate counts (true) or probabilities (false). If unspecified, probabilities will be generated.

The bandwidth (standard deviation) of the Gaussian kernel used in KDE estimation. If 0 or unspecified, the bandwidth will be calculated using Scott's method.

dnExtent : Float -> Float -> DensityProperty

The min (first parameter) - max (second parameter) domain from which to sample a distribution for density estimation. If unspecified, the full extent of input values will be sampled.

The minimum number of samples to take from the extent domain when estimating density. Default is 25.

The maximum number of samples to take when estimating density. Default is 200.

The exact number of samples to take from the extent domain when estimating density. Will override dnMinSteps and dnMaxSteps and is useful in conjunction with a fixed extent to ensure consistent sample points for stacked densities.

dnAs : String -> String -> DensityProperty

Name the outputs of a density transform. The first parameter is the name to give the field containing samples, the second the name to give the field containing density estimates. If not specified, the default names value and density will be used.

3.13 Loess Trend Calculation

See the Vega-Lite loess documentation

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

Generate a loess (locally-estimated scatterplot smoothing) trendline through a pair of data fields. The first parameter is the name of the field representing the dependent variable (commonly mapped to the y-axis), the second is the name of the field representing the independent variable (commonly mapped to the x-axis). The third parameter is a list of optional loess parameters to customise the trend fitting.

lsGroupBy : List String -> LoessProperty

The data fields to group by when generating a loess trendline. If not specified, a single group containing all data objects will be used.

The bandwidth scaled between [0,1] to determine the amount of loess smoothing. Default value is 0.3

lsAs : String -> String -> LoessProperty

Name the outputs of a loess transform. The first parameter is the name to give the field containing the smoothed independent variable, the second the name to give the field containing smoothed dependent variable. If not specified, the original input independent and dependent field names are used.

3.14 Regression Calculation

See the Vega-Lite regression documentation

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

Generate a 2d regression model for smoothing and predicting data. The first parameter is the name of the field representing the dependent variable (commonly mapped to the y-axis), the second is the name of the field representing the independent variable (commonly mapped to the x-axis). The third parameter is a list of optional regression customisation options.

rgGroupBy : List String -> RegressionProperty

The data fields to group by when generating a regression model. If not specified, a single group containing all data objects will be used.

The type of regression model to use when generating a 2d regression.

The order of a polynomial model to use when generating a 2d regression. Only applies if rgMethod is set to rgPoly.

rgExtent : Float -> Float -> RegressionProperty

The min (first parameter) - max (second parameter) domain over which to estimate the dependent variable in a regression. If unspecified, the full extent of input values will be used.

Whether or not the regression transform should return just the parameters of the regression function (one object per group) instead of trend line points. If True, objects include a coef array of fitted coefficient values, starting with the intercept term and then terms of increasing order and an rSquared value, indicating the total variance explained by the model.

rgAs : String -> String -> RegressionProperty

Name the outputs of a regression transform. The first parameter is the name to give the field containing the independent variable, the second the name to give the field containing dependent variable. If not specified, the original input independent and dependent field names are used.

Indicate a linear regression method.

Indicate a log regression method.

Indicate an exponential regression method.

Indicate a power regression method.

Indicate a quadratic regression method.

Indicate a polynomial regression method. The order of the polynomial can be set with rgOrder (defaulting to cubic if not provided).

3.15 Quantile Calculation

String
-> List LabelledSpec
-> List LabelledSpec

Calculate quantile values from an input data stream. Useful for examining distributional properties of a data stream and for creating Q-Q plots.

qtGroupBy : List String -> QuantileProperty

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

qtProbs : List Float -> QuantileProperty

A list of probabilities in the range [0,1] for which to compute quantile values. If not specified, the default step size of 0.01 or the value specified via qtStep will be used.

The interval between probabilities to use when performing a quantile transformation. All values from half the given step size to 1 will be sampled. Only used if qtProbs is not specified.

qtAs : String -> String -> QuantileProperty

The field names to give the probability and associated quantile values generated by a quantile transformation. If not specified, prob and value are used.

3.16 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 aggregate operation to be used in a window transformation.

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

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.


4. Specifying Marks

Functions for declaring the type of visual marks used to represent encoded data.

4.1 Types of Mark

arc : List MarkProperty -> ( VLProperty, Spec )

Arc mark for radial plots such as pie charts or rose diagrams.

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. By default, just box and whiskers are shown, but ticks and outliers can be specified explicitly.

boxplot
    [ maTicks [ maColor "black", maSize 8 ]
    , maBox [ maFill "grey" ]
    , maOutliers [ maColor "firebrick" ]
    ]
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 use maBorders with an empty list for default border, or mark properties to customise.

errorband [ maBorders [ maColor "black", maStrokeWidth 0.5 ] ]
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 use maTicks with an empty list for default appearance, or with a list of mark properties to customise.

errorbar [ maTicks [ maColor "black", maSize 8 ] ]
circle : List MarkProperty -> ( VLProperty, Spec )

Circle mark for symbolising points. Unlike the point mark, circles are filled by default and may be sized via a separate size encoding.

geoshape : List MarkProperty -> ( VLProperty, Spec )

Display a geoshape determined by geographically referenced coordinates.

myMap : Spec
myMap =
    let
        myData =
            dataFromUrl "https://gicentre.github.io/data/geoTutorials/londonBoroughs.json"
                [ topojsonFeature "boroughs" ]


        proj =
            projection
                [ prType transverseMercator
                , prRotate 2 0 0
                ]
    in
    toVegaLite
        [ myData
        , proj
        , geoshape
            [ maFill "lightgrey"
            , maStroke "white"
            ]
        ]
image : List MarkProperty -> ( VLProperty, Spec )

Image mark for displaying an image. The parameter is a list of standard mark properties for customising the image. The image files to be displayed should be specified via the url channel. Normally, the width and height of the image should be specified with maWidth and maHeight.

let
    data =
        dataFromColumns []
            << dataColumn "x" (nums [ 0.5, 1.5, 2.5 ])
            << dataColumn "y" (nums [ 0.5, 1.5, 2.5 ])


    enc =
        encoding
            << position X [ pName "x", pQuant ]
            << position Y [ pName "y", pQuant ]
            << url [ hStr "myImage.png" ]
in
toVegaLite [ data [], enc [], image [ maWidth 50, maHeight 25 ] ]

Alternatively, data-driven images can be used by referencing a data field containing image URLs.

let
    data =
        dataFromColumns []
            << dataColumn "x" (nums [ 0.5, 1.5, 2.5 ])
            << dataColumn "y" (nums [ 0.5, 1.5, 2.5 ])
            << dataColumn "img" (strs [ "img1.png", "img2.png", "img3.png" ])


    enc =
        encoding
            << position X [ pName "x", pQuant ]
            << position Y [ pName "y", pQuant ]
            << url [ hName "img", hNominal ]
in
toVegaLite [ data [], enc [], image [ maWidth 30, maHeight 30 ] ]
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).

maBooExpr : String -> (Bool -> MarkProperty) -> MarkProperty

Provide an expression to a mark property function requiring a boolean value. This can be used to provide an interactive parameterisation of a mark property by providing an expression bound to an input element. For example,

ps =
    params
        << param "asp"
            [ paValue (boo True)
            , paBind (ipCheckbox [ inName "maintain aspect ratio" ])
            ]


mk =
    image [ maBooExpr "asp" maAspect ]
maNumExpr : String -> (number -> MarkProperty) -> MarkProperty

Provide an expression to a mark property function requiring a numeric value. This can be used for interactive parameterisation when an expression is bound to an input element. For example,

ps =
    params
        << param "r"
            [ paValue (num 0)
            , paBind (ipRange [ inMax 100 ])
            ]


mk =
    arc [ maNumExpr "r" maInnerRadius ]
maNumsExpr : String -> (List number -> MarkProperty) -> MarkProperty

Provide an expression to a mark property function requiring a list of numbers (for dash styles). This can be used to provide an interactive parameterisation of a mark's dash property when an expression is bound to an input element. For example,

ps =
    params
        << param "dashStyle"
            [ paValue (nums [ 2, 2 ])
            , paBind (ipSelect [ inDataOptions [ nums [ 2, 2 ], nums [ 8, 8 ] ] ])
            ]


mk =
    bar
        [ maNumsExpr "dashStyle" maStrokeDash, maStroke "black" ]
maStrExpr : String -> (String -> MarkProperty) -> MarkProperty

Provide an expression to a mark property function requiring a string value. This can be used to provide an interactive parameterisation of a mark property by providing an expression bound to an input element. For example,

ps =
    params
        << param "clr"
            [ paValue (str "red")
            , paBind (ipColor [])
            ]


mk =
    circle [ maStrExpr "clr" maFill ]

Horizontal alignment of a text mark.

Rotation angle of a text mark (degrees from horizontal).

ARIA properties for providing accessible SVG output associated with a mark. If an empty list is provided, ARIA tagging will be switched off.

Band size of a bar mark.

Vertical alignment of a text mark.

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

Color blend mode for drawing an item over its current background. Standard CSS blend modes can be specified such as bmHue, bmDarken etc.

Border properties for an errorband mark.

Box symbol properties for the boxplot mark. If an empty list is provided, no box will be shown.

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

Determine whether or not invalid (null and NaN) values are considered for encoding as marks. If true (default), invalid values are ignored, otherwise they are treated as if 0.

maColor : String -> MarkProperty

Default color of a mark. Note that maFill and maStroke have higher precedence and will override this if specified. Color strings can use any valid HTML color specification.

maColor "#eee"


maColor "#734FD8"


maColor "crimson"


maColor "rgb(255,204,210)"


maColor "hsl(180, 50%, 50%)"

A color gradient to apply to a mark. The first parameter indicates whether the gradient should be linear or radial. The second is a set of customisation options for the colors, positioning and rate of change of the gradient. For example, to set a radial red-blue color gradient for a mark:

maColorGradient grRadial [ grStops [ ( 0, "red" ), ( 1, "blue" ) ] ]

The radius in pixels of selected marks' corners. For rectangular marks, it shapes all four corners; for arc marks it shapes the vertices of segment. Default is 0 indicating no rounding.

The radius in pixels of the 'end' corners of a bar mark. For vertical bars this would be the top corners and for horizontal bars, the right corners.

The radius in pixels of the top-left corner of a rectangle mark. Will override any value specified in maCornerRadius.

The radius in pixels of the top-right corner of a rectangle mark. Will override any value specified in maCornerRadius.

The radius in pixels of the bottom-left corner of a rectangle mark. Will override any value specified in maCornerRadius.

The radius in pixels of the bottom-right corner of a rectangle mark. Will override any value specified in maCornerRadius.

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.

Width in pixels indicating maximum permitted space for a text mark. Any mark that exceeds this limit will be truncated with an ellipsis.

maDir : TextDirection -> MarkProperty

Direction of text, which determines which end is truncated in cases where text is larger than available space.

Text to indicate a truncated piece of text (default is the ellipsis ...)

maDx : Float -> MarkProperty

Horizontal offset between a text mark and its anchor.

maDy : Float -> MarkProperty

Vertical offset between a text mark and its anchor.

Fix the inner radius (R2) of a radial plot. Can be used for creating 'holes' in pie chart.

Fix the outer radius (R) of a radial plot.

Angular padding applied to sides of an arc (radians)s.

maFill : String -> MarkProperty

Default fill color of a mark. Color strings can use any valid HTML color specification.

maFill "#eee"


maFill "#734FD8"


maFill "crimson"


maFill "rgb(255,204,210)"


maFill "rgba(255,50,80,0.3)"


maFill "hsl(180, 50%, 50%)"

Usually, to avoid filling the interior of a mark, use maFilled False, but maFill "" can instead be used for cases where an interactive tooltip needs to 'see through' a stroked mark to one underneath it in a layered specification.

A color gradient to apply to a mark's interior. The first parameter indicates whether the gradient should be linear or radial. The second is a set of customisation options for the colors, positioning and rate of change of the gradient. For example, to set a radial red-blue color gradient as a fill for a mark:

maStrokeGradient grRadial [ grStops [ ( 0, "red" ), ( 1, "blue" ) ] ]

Fill gradients have a higher priority than maColorGradient.

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. For example, to create a curved line joining data points:

line [ maInterpolate miMonotone ]

Overall opacity of a mark in the range 0 (completely transparent) to 1 (completely opaque).

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.

line [ maPoint (pmMarker [ maFill "black" ]) ]

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

area
    [ maLine (lmMarker [ maStroke "black" ])
    , maInterpolate miMonotone
    ]

Median line properties for the boxplot mark. If an empty list is provided, no median line will be shown.

Outlier symbol properties for the boxplot mark. If an empty list is provided, no outliers will be shown.

Radial offset of a text mark from an origin specified in Cartesian X and Y coordinates.

Rule (main line) properties for the errorbar and boxplot marks. If an empty list is provided, no rule will be shown.

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. For example, to create a circle of diameter 50 pixels:

circle [ maSize 2500 ]

Default stroke color of a mark. Color strings can use any valid HTML color specification.

maStroke "#eee"


maStroke "#734FD8"


maStroke "crimson"


maStroke "rgb(255,204,210)"


maStroke "hsl(180, 50%, 50%)"

An empty string ("") indicates that no stroke around a mark be drawn.

A color gradient to apply to a mark's boundary stroke. The first parameter indicates whether the gradient should be linear or radial. The second is a set of customisation options for the colors, positioning and rate of change of the gradient. For example, to set a radial red-blue color gradient for a mark's stroke:

maStrokeGradient grRadial [ grStops [ ( 0, "red" ), ( 1, "blue" ) ] ]

Stroke gradients have a higher priority than maColorGradient.

Cap style of a mark's stroke.

Rounded stroke cap.

Square stroke cap.

Butt stroke cap.

caExpr : String -> StrokeCap

Expression that evaluates to some stroke cap style such as "square", "butt" or "round".

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.

joExpr : String -> StrokeJoin

Expression that evaluates to some stroke join style such as "bevel", "miter" or "round".

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 with coMarkStyles. While this is provided for compatibility with Vega-Lite style specification, for greater type safety in elm-vegalite, instead create functions that generate MarkProperties.

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. Multi-line text can be specified by adding a \n at each line break or by using a """ multi-line string.

Line height for multi-line text marks.

Polar coordinate angle (clockwise from north in radians) of an arc or text mark. If a text mark it represents polar coordinate angle relative to an origin determined by its x and y properties. For an arc mark it is its length in radians or, when combined with maTheta2, the arc's start angle.

Polar coordinate angle (clockwise from north in radians) of the end of an arc mark.

Thickness of a tick mark.

Tick properties for the errorbar or boxplot mark.

Provide source of a mark's tooltip content. For example to show all encoded data values in the tooltip of a circle mark:

circle [ maTooltip ttEncoding ]
maUrl : String -> MarkProperty

An image mark's URL.

Explicitly set the width of a mark (e.g. bar width)

Set the width of a mark as a proportion of its band size. For example, to set a bar width to be three quarters of its normal width,

bar [ maWidthBand 0.75 ]

Explicitly set the height of a mark.

Set the height of a mark as a proportion of its band size.

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.

Clockwise angular offset (in radians) of a radially positioned mark.

Clockwise angular offset (in radians) of the second theta value of a radially positioned mark. Useful when the offsets to apply to the start and end angle of an arc need to be set independently.

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.

Polar coordinate radial offset of a text or arc mark from a polar origin specified with Theta and R.

Polar coordinate inner radial offset of an arc mark from a polar origin specified with Theta, R and R2.

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

4.2.1 Color Gradients

Indicate a linear color gradient. See the Vega-Lite color gradient documentation.

Indicate a radial color gradient. See the Vega-Lite color gradient documentation.

The x-coordinate, normalised to [0, 1], for the start of a color gradient. If the gradient is linear the default is 0; if radial, it is the x-position of the centre of the inner circle with a default of 0.5.

The x-coordinate, normalised to [0, 1], for the end of a color gradient. If the gradient is linear the default is 1; if radial, it is the x-position of the centre of the outer circle with a default of 0.5.

The y-coordinate, normalised to [0, 1], for the start of a color gradient. If the gradient is linear the default is 0; if radial, it is the y-position of the centre of the inner circle with a default of 0.5.

The y-coordinate, normalised to [0, 1], for the end of a color gradient. If the gradient is linear the default is 1; if radial, it is the y-position of the centre of the outer circle with a default of 0.5.

The radius, normalised to [0, 1], of the inner circle for a radial color gradient. Default is 0.

The radius, normalised to [0, 1], of the outer circle for a radial color gradient. Default is 0.5.

grStops : List ( Float, String ) -> GradientProperty

Color interpolation points. Each tuple in the list is a position normalised [0, 1] and its associated color.

4.2.2 Used by Mark Properties

Enable ARIA attributes when generating SVG output. Default is that Aria is enabled, so this is only useful when overriding more global disabling of Aria attributes.

Disable ARIA attributes when generating SVG output. Default is that Aria is enabled.

arDescription : String -> Aria

Description to be provided in ARIA tag when generating SVG output. If not specified, the an auto-generated description will be provided.

arExpr : String -> Aria

Set ARIA attributes with the the given expression. For example,

params
    << param "barDesc"
        [ paValue (dataObject [ ( "description", str "Bar chart bar" ) ]) ]


bar [ maAria [ arExpr "barDesc" ] ]

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.

Linear (straight) interpolation between points that joins the first and last points in a sequence to form a closed polygon.

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.

Expression that evaluates to some interpolation method such as "linear", "basis" or "monotone".

tdLeftToRight : TextDirection

Indicate a left-to-right text direction.

tdRightToLeft : TextDirection

Indicate a right-to-left text direction.

tdExpr : String -> TextDirection

Expression that evaluates to a text direction "ltr" (left-to-right) or 'rtl' (right-to-left) .

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.

Specify a leftward facing triangular symbol for a shape mark.

Specify a rightward facing triangular symbol for a shape mark.

symPath : String -> Symbol

A custom symbol shape as an SVG path description.

Specify a linear symbol for a shape mark. Note that this will only be visible if the symbol has a stroke setting (unlike all the other areal symbols filling it has no effect).

Specify a centred arrow symbol for a shape mark. Useful for vector plots.

Specify a centred wedge (thin triangle) symbol for a shape mark. Useful for vector plots.

Specify a centred triangle symbol for a shape mark. Useful for vector plots.

symExpr : String -> Symbol

Expression that evaluates to some symbol such as "diamond", "cross" or "circle".

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. Used when specifying an maPoint.

Properties of a line marker that is overlaid on an area mark. Used when specifying an maLine.

Indicate 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 all fields in the underlying data.

circle [ maTooltip ttData ]

Indicate tooltips should be enabled using the encoded data of the mark.

circle [ maTooltip ttEncoding ]

Indicate that tooltips should be disabled for the mark (default).

circle [ maTooltip ttNone ]

4.2.3 Blend Modes

Indicate the default blend mode should be applied when drawing over some background.

Multiplicative blend mode to be applied when drawing over some background.

Screen blend mode to be applied when drawing over some background.

Overlay blend mode to be applied when drawing over some background.

Darken blend mode to be applied when drawing over some background.

Lighten blend mode to be applied when drawing over some background.

Color dodge blend mode to be applied when drawing over some background.

Color burn blend mode to be applied when drawing over some background.

Hard light blend mode to be applied when drawing over some background.

Soft light blend mode to be applied when drawing over some background.

Difference blend mode to be applied when drawing over some background.

Exclusion blend mode to be applied when drawing over some background.

Hue blend mode to be applied when drawing over some background.

Saturation blend mode to be applied when drawing over some background.

Color blend mode to be applied when drawing over some background.

Luminosity blend mode to be applied when drawing over some background.

bmExpr : String -> BlendMode

Expression that evaluates to some blend mode such as "darken", "hue" or "luminosity".

4.2.4 Cursors

See the CSS cursor documentation

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.

cuExpr : String -> Cursor

Expression that evaluates to some cursor style such as "crosshair", "grab" or "help".


5. Encoding Data as Channels

Describes the mapping between data fields and the channels (position, color etc.) used to determine the visual appearance of marks that represent them.

encoding : List LabelledSpec -> ( VLProperty, Spec )

Create an encoding specification from a list of channel encodings. These are commonly built by chaining series of channel encoding functions together such as position, color, size etc.

enc =
    encoding
        << position X [ pName "month", pTemporal ]
        << position Y [ pName "score", pQuant ]
        << color [ mName "team" ]

Type of measurement to be associated with some channel.

  • Nominal indicates categories that have no order. e.g. people's names; country names.
  • Ordinal indicates ordered categories. e.g. Small / Medium / Large; 1st, 2nd, 3rd.
  • Quantitative indicates numerical measurements and counts. e.g. price; temperature; frequency.
  • Temporal indicates time-related data.
  • GeoFeature indicates one or more geographic locations. e.g. a longitude/latitude; country outline.

5.1 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 position encoding options.

enc =
    encoding
        << position X [ pName "month", pTemporal ]
        << position Y [ pName "numHires", pQuant ]
= X
| Y
| X2
| Y2
| XOffset
| YOffset
| Theta
| Theta2
| R
| R2
| Longitude
| Latitude
| Longitude2
| Latitude2
| XError
| YError
| XError2
| YError2

Type of position channel. X and Y position marks along the horizontal and vertical axes. X2 and Y2 are used in combination with X and Y when two boundaries of a mark need to be specified (e.g. a rule mark). XOffset and YOffset can additional shift position in response to some field, for example to create a grouped bar chart or jitter-plot.

Theta positions an arc mark's angular offset allowing, for example, pie chart segments to be specified. Theta2 allows an end angle to be specified in radians (where 0 is 'north'), useful for individual 'pie' segments.

R and R2 position the outer and inner radial edges of an arc segment. Useful for rose diagrams where arc radii are data-driven.

Longitude/Longitude2 and Latitude/Latitude2 are the equivalent for geographic positioning subject to projection.

XError/XError2 and YError/YError2 are used when specifying bounds of an errorbar mark.

5.1.1 Position Channel Properties

Name of field used for encoding with a position channel.

Set a position to an arbitrary data value. Useful for placing items at the specific points in the data space. To place in data screen space, use pNum.

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 encoded in layers, or in columns / rows with a flow layout.

enc =
    encoding
        << position X [ pRepeat arFlow, pQuant ]


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


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

Reference in a position channel to a datum value generated by repeat.

Indicate a data field encoded as a position is nominal. This is the default data type.

Indicate a data field encoded as a position is ordinal.

Indicate a data field encoded as a position is quantitative. This is not necessary when field is aggregated by a numeric operator (e.g. opSum), scaled with a numeric operator (e.g. scLog), a position field is longitude/latitude or it is binned numerically.

Indicate a data field encoded as a position is temporal. This is not necessary if the field is aggregated with a time unit (e.g. pTimeUnit) or scaled with scTime or scUtc.

Indicate a data field encoded as a position is a geo feature.

Discretize numeric values into bins when encoding with a position channel. For non-default binning, bin-widths, extent etc. can be specified in the first parameter. For example, to encode a frequency histogram with bins every 5 units:

enc =
    encoding
        << position X [ pName "x", pOrdinal, pBin [ biStep 5 ] ]
        << position Y [ pQuant, pAggregate opCount ]

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. For multi-line titles, insert \n at each line break or use a """ multi-line string.

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.

enc =
    encoding
        << position X [ pName "role", pOrdinal ]
        << position Y [ pName "salary", pQuant, pAggregate opMean ]

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.

For example, the following will scale the bars positioned along a horizontal axis to have an inner spacing of 50% (0.5) of the total space allocated to each bar:

enc =
    encoding
        << position X [ pName "ageGroup", pNominal, pScale [ scPaddingInner 0.5 ] ]

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.

Specify mark position or size relative to band size. For non-rect marks, the relative position on a band of a stacked, binned, time unit or band scale is used. A value of 0, positions the mark at the beginning of the band; 0.5, in the middle etc.

For rect-based marks (rect, bar, and image), if set to 1, the mark size is set to the band width or the time unit interval. If set to 0.5, the mark size is half of the bandwidth or the time unit interval. etc.

Type of stacking offset for field when encoding with a position channel. For example, stacking areas away from a centre-line can be used to create a streamgraph:

enc =
    encoding
        << position X [ pName "week", pOrdinal ]
        << position Y [ pName "takings", pQuant, pStack stCenter ]
        << color [ mName "shop", mNominal ]

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. To place in data space rather than screen space, use pDatum.

Imputation rules for a position channel. See the Vega-Lite impute documentation For example, to impute the missing value of b with the mean of existing b values, when a is 30 and its color group (c) is 1:

let
    data =
        dataFromColumns []
            << dataColumn "a" (nums [ 0, 0, 10, 10, 20, 20, 30 ])
            << dataColumn "b" (nums [ 28, 91, 43, 55, 81, 53, 19 ])
            << dataColumn "c" (nums [ 0, 1, 0, 1, 0, 1, 0 ])


    enc =
        encoding
            << position X [ pName "a", pQuant ]
            << position Y [ pName "b", pQuant, pImpute [ imMethod imMean ] ]
            << color [ mName "c", mNominal ]
in
toVegaLite [ data [], enc [], line [] ]

5.1.2 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"
    , pOrdinal
    , pSort [ soByField "age" opMean, soDescending ]
    ]

Sort by another channel.

position Y [ pName "age", pOrdinal, 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.

5.1.3 Axis Properties

See the Vega-Lite axis property documentation

axBooExpr : String -> (Bool -> AxisProperty) -> AxisProperty

Provide an expression to an axis property function requiring a Boolean value. This can be used to provide an interactive parameterisation of an axis property when an expression is bound to an input element. For example,

ps =
    params
        << param "lbls"
            [ paValue (boo True)
            , paBind (ipCheckbox [])
            ]


enc =
    encoding
        << position X
            [ pName "x"
            , pAxis [ axBooExpr "lbls" axLabels ]
            ]
axcoBooExpr : String -> (Bool -> AxisConfig) -> AxisConfig

Provide an expression to an axis configuration function requiring a Boolean value.

axNumExpr : String -> (number -> AxisProperty) -> AxisProperty

Provide an expression to an axis property function requiring a numeric value. This can be used for interactive parameterisation when an expression is bound to an input element. For example,

ps =
    params
        << param "axo"
            [ paValue (num 0)
            , paBind (ipRange [ inMax 20 ])
            ]


enc =
    encoding
        << position X
            [ pName "x"
            , pAxis [ axNumExpr "axo" axOffset ]
            ]
axcoNumExpr : String -> (number -> AxisConfig) -> AxisConfig

Provide an expression to an axis property configuration function requiring a numeric value.

axNumsExpr : String -> (List number -> AxisProperty) -> AxisProperty

Provide an expression to an axis property function requiring a list of numbers (for dash styles). This can be used to provide an interactive parameterisation of an axis dash property when an expression is bound to an input element. For example,

ps =
    params
        << param "gridDash"
            [ paValue (nums [ 2, 2 ])
            , paBind (ipSelect [ inDataOptions [ nums [ 2, 2 ], nums [ 8, 8 ] ] ])
            ]


enc =
    encoding
        << position X [ pAxis [ axNumsExpr "gridDash" axGridDash ] ]
axcoNumsExpr : String -> (List number -> AxisConfig) -> AxisConfig

Provide an expression to an axis configuration function requiring a list of numbers (for dash styles).

axStrExpr : String -> (String -> AxisProperty) -> AxisProperty

Provide an expression to an axis property function requiring a string value. This can be used to provide an interactive parameterisation of an axis property when an expression is bound to an input element. For example,

ps =
    params
        << param "color"
            [ paValue (str "black")
            , paBind (ipColor [])
            ]


enc =
    encoding
        << position X
            [ pName "x"
            , pAxis [ axStrExpr "color" axTitleColor ]
            ]
axcoStrExpr : String -> (String -> AxisConfig) -> AxisConfig

Provide an expression to an axis property function requiring a string value. This can be used to provide an interactive parameterisation of an axis property when an expression is bound to an input element. For example,

ps =
    params
        << param "color"
            [ paValue (str "black")
            , paBind (ipColor [])
            ]


enc =
    encoding
        << position X
            [ pName "x"
            , pAxis [ axStrExpr "color" axTitleColor ]
            ]

General

ARIA properties for providing accessible SVG output associated with an axis. If an empty list is provided, ARIA tagging will be switched off.

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

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

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

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

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

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.

Drawing order of the axis and its associated features (grid lines, ticks etc.) relative to the other chart elements. A value greater than 0 indicates axis is drawn in front of chart marks, 0 indicates it is drawn behind them. The z-order of intersecting grid lines associated with x- and y- axes can be controlled by assigning a higher z-value to the axis to appear on top.

Make an axis property (tick, grid or label) conditional on one or more predicate expressions. The first parameter is the test to apply. The second is a pair of properties to set if the test evaluates to true or false.

The test parameter has access to the axis properties value and label corresponding to the value associated with an individual axis element and its text label. These should be used rather than the underlying data field when referencing a data value.

 pAxis
    [ axDataCondition (expr "datum.value <= 2")
        (cAxTickColor "red" "blue")
    , axDataCondition (expr "datum.label =='4.0'")
        (cAxTickWidth 5 2)
    ]

You can also apply inline aggregation before applying the test using fiOpTrans, which can be particularly useful for filtering temporal data. For example, the following will apply solid grid lines for January 1st of each year and dashes for all other dates:

pAxis
    [ axDataCondition
        (fiEqual "value" (dt [ dtMonth Jan, dtDate 1 ])
            |> fiOpTrans (mTimeUnit monthDate)
        )
        (cAxGridDash [] [ 2, 2 ])
    ]
axStyle : List String -> AxisProperty

A list of named styles to apply to an axis. Named styles can be specified via coAxisStyles. Later styles in the list will override earlier styles if there is a conflict in any of the properties specified.

While this is provided for compatibility with Vega-Lite style specification, for greater type safety in elm-vegalite, instead create functions that generate AxisProperties.

Coordinate space translation offset for axis layout. By default, axes are translated by 0.5 pixels for both the x and y coordinates in order to align stroked lines with the pixel grid. This translation can be changed, for example, to zero.

Axis Domain

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

axDomainDash : List Float -> AxisProperty

Dash style of axis baseline (domain). The parameter should list number of pixels in alternating dash and gap lengths.

Number of pixels before the first axis baseline (domain) line dash is drawn.

How the ends of the axis baseline (domain) are capped.

Color of axis domain line.

Opacity of axis domain line.

Width of axis domain line.

Axis Labels

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

Specify multiple time formats for axis labels that might vary according to the temporal resolution. This is especially useful when used with paBindScales that will adjust the granularity of time labels dynamically. The parameter is a list of time units to customise and their respective formatting pattern. For example,

pAxis
    [ axTemporalFormats
        [ ( year, "`%Y" )
        , ( hours, "kl %-H" )
        , ( minutes, "%H:%M" )
        ]
    ]

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, use axFormat or axTemporalFormats providing d3 date/time format strings.

Indicate that axis labels should be formatted with a registered custom formatter with the given name. See how to register a Vega-Lite custom formatter.

Whether or not axis labels should be displayed.

Horizontal alignment of axis tick labels.

Conditional axis label alignment. The first parameter provides the alignment when a predicate is true, the second when it is false.

Rotation angle of axis labels (degrees from horizontal).

Vertical alignment of axis tick labels.

Conditional axis vertical label alignment. The first parameter provides the alignment when a predicate is true, the second when it is false.

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.

Expression that evaluates to True, False or a number depending whether a check is to be made for an axis label size. A number specifies the permitted overflow in pixels.

Color of axis tick label.

Conditional axis label color. The first parameter provides the color when a predicate is true, the second when it is false.

An expression to generate axis labels. The parameter is a valid Vega expression. Can reference datum.value and datum.label for access to the underlying data values and default label text respectively. For example, to provide 4 digit years every decade and 2-digit years for all other tick marks:

pAxis
    [ axLabelExpr "if(year(datum.value) % 10 == 0"
        ++ ", utcFormat(datum.value,'%Y')"
        ++ ", utcFormat(datum.value,'%y'))"
    ]
axLabelFlush : Maybe Float -> AxisProperty

How or if labels at beginning and 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.

Conditional axis label font. The first parameter provides the font when a predicate is true, the second when it is false.

Font size of an axis label.

Conditional axis label font size. The first parameter provides the size when a predicate is true, the second when it is false.

Font style of an axis label (e.g. "italic")

Conditional axis label font style. The first parameter provides the style when a predicate is true, the second when it is false.

Font weight of an axis label.

Conditional axis label font weight. The first parameter provides the weight when a predicate is true, the second when it is false.

Maximum length in pixels of axis tick labels.

Axis label line height (useful for multi-line labels).

Offset in pixels of an axis's labels relative to its ticks.

Conditional axis label offset. The first parameter provides the offset when a predicate is true, the second when it is false.

Opacity of an axis label.

Conditional axis label opacity. The first parameter provides the opacity when a predicate is true, the second when it is false.

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.

Conditional axis label padding. The first parameter provides the padding when a predicate is true, the second when it is false.

The minimum separation between labels (in pixel units) before they are considered non-overlapping. Ignored if axLabelOverlap is osNone.

Axis Ticks

Whether or not an axis should include tick marks.

axTickBand : TickBand -> AxisProperty

Where grid and ticks should be aligned with bands.

tbCenter : TickBand

Align to centre of tick band.

tbExtent : TickBand

Align to extent (edges) of tick band.

tbExpr : String -> TickBand

Specify a tick band alignment with an expression that should evaluate to "center" or "extent".

How the ends of axis ticks are capped.

Color of axis ticks.

Conditional axis tick color. The first parameter provides the color when a predicate is true, the second when it is false.

Desired number of, or interval between, axis ticks. The resulting number of ticks may be different so that values are “nice” (multiples of 2, 5, 10).

axTickDash : List Float -> AxisProperty

Axis tick dash style. The parameter is a list of alternating 'on' and 'off' lengths in pixels representing the dashed line.

cAxTickDash : List Float -> List Float -> ConditionalAxisProperty

Conditional axis tick dash style. The first parameter is a list of alternating 'on' and 'off' lengths in pixels representing the dashed line when a predicate is true, the second when it is false.

Number of pixels before the first axis tick dash is drawn.

Conditional axis tick dash offset. The first parameter provides the dash offset when a predicate is true, the second when it is false.

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

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.

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

Opacity of axis ticks.

Conditional axis tick opacity. The first parameter provides the opacity when a predicate is true, the second when it is false.

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

Tick mark size in pixels.

Conditional axis tick size. The first parameter provides the size when a predicate is true, the second when it is false.

Width of axis ticks.

Conditional axis tick width. The first parameter provides the width when a predicate is true, the second when it is false.

Set explicit tick/grid/label values along an axis. For example, for a quantitative field:

pAxis [ axValues (nums [ 2, 3, 5, 7, 11, 13, 17 ]) ]

or a categorical field:

pAxis [ axValues (strs [ "cats", "dogs", "parrots" ]) ]

or for a temporal field:

pAxis
    [ axValues
        (dts
            [ [ dtYear 2019, dtMonth Mar, dtDate 31 ]
            , [ dtYear 2019, dtMonth Jun, dtDate 30 ]
            , [ dtYear 2019, dtMonth Sep, dtDate 30 ]
            , [ dtYear 2019, dtMonth Dec, dtDate 31 ]
            ]
        )
    ]

Axis Title

axTitle : String -> AxisProperty

Title to display as part of an axis. An empty string can be used to prevent a title being displayed. For multi-line titles, insert \n at each line break or use a """ multi-line string.

Horizontal alignment of an axis title.

Anchor position of an axis title.

Angle of an axis title (degrees from horizontal).

Vertical alignment of axis title.

Color of axis title.

Font name for an axis title.

Font size of an axis title.

Font style of an axis title (e.g. "italic").

Font weight of an axis title.

Maximum length in pixels of axis title.

Line height for multi-line axis titles.

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.

Axis Grid

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

How the ends of gridlines are capped.

Color of grid lines associated with an axis.

Conditional axis grid color. The first parameter provides the color when a predicate is true, the second when it is false.

axGridDash : List Float -> AxisProperty

Axis grid lines dash style. The parameter is a list of alternating 'on' and 'off' lengths in pixels representing the dashed line.

cAxGridDash : List Float -> List Float -> ConditionalAxisProperty

Conditional axis grid dash. The first parameter provides the dash when a predicate is true, the second when it is false.

Default number of pixels before the first axis grid line dash is drawn.

Conditional axis grid dash offset. The first parameter provides the dash offset when a predicate is true, the second when it is false.

Opacity of grid lines associated with an axis.

Conditional axis grid opacity. The first parameter provides the opacity when a predicate is true, the second when it is false.

Width of grid lines associated with an axis.

Conditional axis grid width. The first parameter provides the width when a predicate is true, the second when it is false.

5.1.4 Positioning Constants

Text Alignment

Left horizontal text alignment.

Center horizontal text alignment.

Right horizontal text alignment.

haExpr : String -> HAlign

Expression that evaluates to some text alignment such as "left", "right" or "center". Can be used, for example, to align text to the left or right depending on whether data values are positive or negative:

maAlign (haExpr "datum.x < 0 ? 'right' : 'left'")

Vertically align text marks by the top of ascenders (e.g. top of an 'A').

Vertically align text marks by the top of the space defined by line height (maLineHeight, tiLineHeight etc.).

Vertically align text marks by their middle (e.g. middle of an 'x').

Vertically align text marks by the bottom of descenders (e.g. bottom of a 'g').

Vertically align text marks by the bottom of the space defined by line height (maLineHeight, tiLineHeight etc.).

Vertically align text marks by their baseline (e.g. bottom of an 'x').

vaExpr : String -> VAlign

Expression that evaluates to some vertical text alignment such as "top", "bottom" or "alphabetic".

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.

Specify an overlap strategy with an expression that should evaluate to one of True, False, "parity" or "greedy". If using an input element such as ipSelect to allow all options, the mixed option types should be defined with inDatumOptions, for example:

ipSelect
    [ inName "Label overlap"
    , inDatumOptions [ boo False, str "parity", str "greedy" ]
    ]

Relative Position

Top side, used, for example, to specify an axis position.

Bottom side, used, for example, to specify an axis position.

Left side, used, for example, to specify an axis position.

Right side, used, for example, to specify an axis position.

siExpr : String -> Side

Specify a side position with an interactive expression.

5.2 Mark Channels

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. The first parameter is a list of size encoding options such as the data to encode, size scaling etc.

enc =
    encoding
        << size [ mName "population", mQuant ]
angle : List MarkChannel -> List LabelledSpec -> List LabelledSpec

Encode an angle (orientation) channel. This allows data-driven rotation of text, point-based marks.

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

Encode a color channel. The first parameter is a list of color encoding options such as the data to encode, colour scaling etc.

enc =
    encoding
        << color [ mName "avHireTime", mQuant ]
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.

strokeDash : List MarkChannel -> List LabelledSpec -> List LabelledSpec

Encode a stroke dash channel.

enc =
    encoding
        << position X [ pName "date", pTemporal ]
        << position Y [ pName "price", pQuant ]
        << strokeDash [ mName "company" ]
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. The first parameter is a list of shape encoding options such as the data to encode, custom shape encodings etc.

enc =
    encoding
        << shape [ mName "company", mNominal ]

5.2.1 Mark Channel Properties

mName : String -> MarkChannel

Name of field used for encoding with a mark property channel.

Name of a literal data item used for encoding with a mark property channel. Unlike mNum, mStr and mBoo, datum literals represent values in data space.

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 encoded in layers, or in columns / rows with a flow layout.

Reference in a mark channel to a datum value generated by repeatFlow or repeat. The parameter identifies whether reference is being made to a datum that is to be encoded in layers, or in columns / rows with a flow layout.

Indicate a data field encoded as a mark property is nominal. This is the default data type.

Indicate a data field encoded as a mark property is ordinal.

Indicate a data field encoded as a mark property is quantitative.

Indicate a data field encoded as a mark property is temporal.

Indicate a data field encoded as a mark property is a geo feature.

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.

mBand : Float -> MarkChannel

Apply offset relative to band width for a mark property. Value should be in the range [0, 1] as a proportion of the band width.

Sort order when encoding sortable mark properties such as colour.

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. For multi-line titles, insert \n at each line break or use a """ multi-line string.

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 the 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 symbol literal when encoding with a mark property channel. Can be useful when making a symbol dependent on some data or selection condition.

5.2.2 Mark Legends

See the Vega-Lite legend property documentation.

leNumExpr : String -> (number -> LegendProperty) -> LegendProperty

Provide an expression to a legend property function requiring a numeric value. This can be used for interactive parameterisation when an expression is bound to an input element. For example,

ps =
    params
        << param "xPos"
            [ paValue (num 0)
            , paBind (ipRange [ inMax 100 ])
            ]


enc =
    encoding
        << color
            [ mName "animal"
            , mLegend [ leNumExpr "xPos" leX ]
            ]
lecoNumExpr : String -> (number -> LegendConfig) -> LegendConfig

Provide an expression to a legend configuration function requiring a numeric value.

leNumsExpr : String -> (List number -> LegendProperty) -> LegendProperty

Provide an expression to a legend property function requiring a list of numbers (for dash styles). This can be used to provide an interactive parameterisation of an axis dash property when an expression is bound to an input element. For example,

ps =
    params
        << param "dashStyle"
            [ paValue nums []
            , paBind (ipSelect [ inDataOptions [ nums [ 2, 2 ], nums [ 8, 8 ] ] ])
            ]


enc =
    encoding
        << color
            [ mName "country"
            , mLegend [ leNumsExpr "dashStyle" leSymbolDash ]
            ]
lecoNumsExpr : String -> (List number -> LegendConfig) -> LegendConfig

Provide an expression to a legend property configuration requiring a list of numbers (for dash styles).

leStrExpr : String -> (String -> LegendProperty) -> LegendProperty

Provide an expression to an legend property function requiring a string value. This can be used to provide an interactive parameterisation of a legend property when an expression is bound to an input element. For example,

ps =
    params
        << param "color"
            [ paValue (str "black")
            , paBind (ipColor [])
            ]


enc =
    encoding
        << color
            [ mName "animal"
            , mLegend [ leStrExpr "color" leTitleColor ]
            ]
lecoStrExpr : String -> (String -> LegendConfig) -> LegendConfig

Provide an expression to an legend configuration function requiring a string value.

ARIA properties for providing accessible SVG output associated with a legend. If an empty list is provided, ARIA tagging will be switched off.

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, leFormatAsTemporal or leFormatAsCustom.

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.

Indicate that legend labels should be formatted with a registered custom formatter with the given name. See how to register a Vega-Lite custom formatter.

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

Default maximum length in pixels of a horizontal color ramp legend.

Default minimum length in pixels of a horizontal color ramp legend.

Default maximum length in pixels of a vertical color ramp legend.

Default minimum length in pixels of a vertical color ramp legend.

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

An expression to generate legend labels. The parameter is a valid Vega expression. Can reference datum.value and datum.label for access to the underlying data values and default label text respectively. For example, to show just the first word of each legend category:

mLegend [ leLabelExpr "split(datum.value,' ')[0]" ]

Font for legend labels.

Font size legend labels.

Font style (e.g italic) for legend labels.

Font weight for 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 dash style in legend encoding.

Legend symbol dash offset in legend encoding.

Legend symbol fill color.

Maximum number of symbols in a legend.

Symbol offset between legend symbols and legend area.

Legend symbol opacity.

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. For multi-line titles, insert \n at each line break or use a """ multi-line string.

Horizontal alignment for legend titles.

Horizontal alignment for legend titles.

Vertical alignment for legend titles.

Color for legend title.

Font for legend titles.

Font size for legend titles.

Font style (italic etc.) for legend titles.

Font weight for legend titles.

Maximum size in pixel units for legend titles.

Height in pixels for each line of a multi-line legend title.

Opacity of a legend's title.

Position of a legend's title relative to the main legend content.

Spacing in pixel units between title and legend.

Type of legend.

An explicit set of legend values.

leX : Float -> LegendProperty

x-position of legend group in pixel units for absolute positioning when leOrient is set to loNone.

leY : Float -> LegendProperty

y-position of legend group in pixel units for absolute positioning when leOrient is set to loNone.

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.

Legend Constants

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

5.3 Text Channel

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. The first parameter is a list of text encoding options such as the data to encode, number formatting etc.

enc =
    encoding
        << text [ tName "keyword", tNominal ]
tooltip : List TextChannel -> List LabelledSpec -> List LabelledSpec

Encode a tooltip channel using a single data field.

 tooltip [ tName "Month", tTemporal, tFormat "%B %Y" ]

To encode multiple tooltip values with a mark, use tooltips. This is also useful if you wish the field name to be displayed along with the value, as by default, tooltip will only show the value.

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

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

tooltips
    [ [ tName "month", tTemporal, tFormat "%B %Y" ]
    , [ tName "temperature", tQuant ]
    ]

Thsi multi-tooltip version (rather than tooltip) should also be used if you wish to display images in tooltips. For example,

tooltips [ [ tName "image" ] ]
tName : String -> TextChannel

Name of 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.

Indicate a data field encoded as a text property is nominal. This is the default data type.

Indicate a data field encoded as a text property is ordinal.

Indicate a data field encoded as a text property is quantitative.

Indicate a data field encoded as a text property is temporal.

Indicate a data field encoded as a text property is a geo feature.

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. For multi-line titles, insert \n at each line break or use a """ multi-line string.

tStr : String -> TextChannel

Literal string value when encoding with a text channel. Can be useful for quick text annotation. For multi-line text, insert \n at each line break or use a """ multi-line string.

encoding
    << position X [ pNum 300 ]
    << position Y [ pNum 300 ]
    << text [ tStr "Upper limit\nof range" ]

Name of a literal data item used for encoding with a text channel. Unlike tStr datum literals represent values in data space.

tFormat : String -> TextChannel

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

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.

Indicate that values encoded with a text channel should be formatted with a registered custom formatter with the given name. See how to register a Vega-Lite custom formatter.

Specify a bold font weight.

Specify a bolder font weight.

Specify a lighter font weight.

Specify a normal font weight.

Specify a numeric font weight that should be between 100 (lightest) and 900 (boldest).

fwExpr : String -> FontWeight

Expression that evaluates to some font weight such as "bold", "lighter" or "600".

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

Name of 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.

Indicate a data field encoded as a hyperlink or url property is nominal. This is the default data type.

Indicate a data field encoded as a hyperlink property is ordinal.

Indicate a data field encoded as a hyperlink or url property is quantitative.

Indicate a data field encoded as a hyperlink or url property is temporal.

Indicate a data field encoded as a hyperlink property is a geo feature.

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.

5.5 URL Channel

Data-driven URL used for image specification. A data field can contain URL strings defining the location of image files that can be shown with the image mark.

url : List HyperlinkChannel -> List LabelledSpec -> List LabelledSpec

Encode a url channel. The first parameter is a list of url channel properties that characterise the hyperlink to encode with. This is used for specifying data-driven image files for the image mark.

encData =
    encoding
        << url [ hName "url", hNominal ]


encLiteral =
    encoding
        << url [ hStr "http://www.imdb.com" ]

5.6 Order Channel

Channel 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. The first parameter is a list of order encoding options such as the data to encode, sort direction etc.

enc =
    encoding
        << order [ oName "yield", oOrdinal, oSort [ soDescending ] ]
oName : String -> OrderChannel

Name of 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.

Indicate a data field encoded with an order channel is nominal.

Indicate a data field encoded with an order channel is ordinal.

Indicate a data field encoded with an order channel is quantitative.

Indicate a data field encoded with an order channel is temporal.

Indicate a data field encoded with an order channel is a geo feature.

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.

oNum : Float -> OrderChannel

Specify a literal numeric value for an order channel. Useful for setting a conditional z-order with interaction to bring selected feature to 'front'.

5.7 Facet Channels

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

Note that when faceting, dimensions specified with width and height refer to the individual faceted plots, not the assemblage as a whole.

let
    data =
        dataFromUrl "crimeData.csv"


    enc =
        encoding
            << position X [ pName "month", pTemporal ]
            << position Y
                [ pName "reportedCrimes"
                , pQuant
                , pAggregate opSum
                , pTitle ""
                ]
            << row [ fName "crimeType", fNominal ]
in
toVegaLite [ height 80, data [], bar [], enc [] ]
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

Note that when faceting, dimensions specified with width and height refer to the individual faceted plots, not the assemblage as a whole.

let
    data =
        dataFromUrl "crimeData.csv"


    enc =
        encoding
            << position X [ pName "month", pTemporal ]
            << position Y [ pName "reportedCrimes", pQuant, pAggregate opSum ]
            << column [ fName "crimeType", fNominal ]
in
toVegaLite [ width 100, data [], bar [], enc [] ]

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

enc =
    encoding
        << detail [ dName "avHireTime", dQuant ]
dName : String -> DetailChannel

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

Indicate a data field encoded with a detail channel is nominal. This is the default data type.

Indicate a data field encoded with a detail channel is ordinal.

Indicate a data field encoded with a detail channel is quantitative.

Indicate a data field encoded with a detail channel is temporal.

Indicate a data field encoded with a detail channel is a geo feature.

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.

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

5.9 Key Channel

Enables object constancy for transitions over dynamic data. When a visualization’s data is updated (via the Vega View API, the key value will be used to match data elements to existing mark instances. See the Vega-Lite key channel documentation.

key : List KeyChannel -> List LabelledSpec -> List LabelledSpec

Encode a key channel for use with the Vega View API. The first parameter identifies a list of key encoding options (just the name of the data field to use as a unique key for data binding and its type).

kName : String -> KeyChannel

Name of field used for encoding with a key channel.

Indicate a data field encoded as a key channel property is nominal. This is the default data type.

Indicate a data field encoded as a key channel property is ordinal.

Indicate a data field encoded as a key channel property is quantitative.

Indicate a data field encoded as a key channel property is temporal.

Indicate a data field encoded as a key channel property stores geo-features.

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

scNumExpr : String -> (number -> ScaleProperty) -> ScaleProperty

Provide an expression to a scale property function requiring a numeric value. This can be used to provide an interactive parameterisation of a mark property by providing an expression bound to an input element. For example,

ps =
    params
        << param "pad"
            [ paValue (num 0)
            , paBind (ipRange [ inMax 100 ])
            ]


enc =
    encoding
        << position X [ mName "val" mScale [ scNumExpr "pad" scPadding ] ]
scBooExpr : String -> (Bool -> ScaleProperty) -> ScaleProperty

Provide an expression to a scale property function requiring a Boolean value. This can be used to provide an interactive parameterisation of a mark property by providing an expression bound to an input element. For example,

ps =
    params
        << param "rev"
            [ paValue (boo False)
            , paBind (ipCheckbox [ inName "reverse colours" ])
            ]


enc =
    encoding
        << color [ mName "val" mScale [ scBooExpr "rev" scReverse ] ]

5.10.1 Scale Domain

Describes the data values that will be encoded.

doNumExpr : String -> (number -> ScaleDomain) -> ScaleDomain

Provide an expression to a domain scale property function requiring a numeric value. This can be used for interactive parameterisation when an expression is bound to an input element. For example,

ps =
    params
        << param "upper"
            [ paValue (num 50)
            , paBind (ipRange [ inMax 100 ])
            ]


enc =
    encoding
        << position X
            [ pName "x"
            , pScale [ scDomain (doNumExpr "upper" doMax) ]
            ]

Provide a custom scaling domain (data extent). This can be useful for fixing the data extent when interactively filtering or faceting so providing a 'global' scaling consistent across views. For example:

color
    [ mName "popularity"
    , mQuant
    , mScale [ scDomain (doNums [ 0, 100 ]) ]
    ]

Expression that defines a scaling domain.

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

Create a set of discrete domain to range mappings suitable for customising categorical scales. The first item in each tuple should be a domain value and the second the range 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. This is typically used to provide discrete colors for categorical variables.

color
    [ mName "weather"
    , mNominal
    , categoricalDomainMap
        [ ( "sun", "yellow" )
        , ( "rain", "blue" )
        , ( "fog", "grey" )
        ]
        |> mScale
    ]
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"
    , mOrdinal
    , mScale (domainRangeMap ( 1955, "#e6959c" ) ( 2000, "#911a24" ))
    ]
doNums : List Float -> ScaleDomain

Numeric values that define a scale domain.

doMin : Float -> ScaleDomain

Set the minimum value of a continuous numeric domain. The maximum will be determined by the data. To set both the min and max values use doNums.

doMid : Float -> ScaleDomain

Set the midpoint of continuous two-point diverging domain. Useful when the domain is not symmetric about the given midpoint but you wish to use a color scheme that diverges equally from that point.

doMax : Float -> ScaleDomain

Set the maximum value of a continuous numeric domain. The minimum will be determined by the data. To set both the min and max values use doNums.

doStrs : List String -> ScaleDomain

String values that define a scale domain.

doDts : List (List DateTime) -> ScaleDomain

Date-time values that define a scale domain.

Expression that should evaluate to a list of date-times that define a scale domain.

Set the minimum value of a date-time domain. The maximum will be determined by the data. To set both the min and max values use doDts.

Set the minimum value of a date-time domain with an expression that evaluates to a date-time.

Set the maximum value of a date-time domain. The minimum will be determined by the data. To set both the min and max values use doDts.

Set the maximum value of a date-time domain with an expression that evaluates to a date-time.

Indicate that a domain of aggregated data should be scaled to the domain of the data prior to aggregation.

Combine the given domain with that determined by the data. This allows a minimal domain to be set that may be exceeded if the data determine so. For example, the following sets a domain of at least 0 to 100, but can be exceeded if the data extend beyond the domain:

pScale [ scDomain (doUnionWith (doNums [ 0, 100 ])) ]

Scale domain based on a named interactive selection. This can be used when projecting a selection across a single domain or equally across several domains.

Scale domain based on a named interactive selection (first parameter) and project it across the given channel (second parameter). Useful when, for example, you wish to project a 2d interval selection across the X and Y channels each with independent domains.

doSelectionField : String -> String -> ScaleDomain

Scale domain based on a named interactive selection (first parameter) and project it across the given field (second parameter). Useful when, for example, you wish to project a 2d interval selection across the X and Y channels each with independent domains.

5.10.2 Scale Range

Describes the values after data have been encoded (e.g. pixel positions or color values).

raNumExpr : String -> (number -> ScaleRange) -> ScaleRange

Provide an expression to a range scale property function requiring a numeric value. This can be used for interactive parameterisation when an expression is bound to an input element. For example,

ps =
    params
        << param "right"
            [ paValue (num 0)
            , paBind (ipRange [ inMax 500 ])
            ]


enc =
    encoding
        << position X
            [ pName "x"
            , pScale [ scRange (raNumExpr "right" raMax) ]
            ]

Provide a custom range of an encoding scaling. In contrast to the domain (data), the range describes the values after they have been encoded. For example, when encoding some data as size, the range will be in squared pixel units; when encoding with color, the range will be some colour values.

For example, to set the size range of proportional symbols to be between 0 and 1000 squared pixels:

size
    [ mName "magnitude"
    , mQuant
    , mScale [ scRange (raNums [ 0, 1000 ]) ]
    ]
raExprs : List String -> ScaleRange

A list of expressions that each evaluate to an element of a scale range. For example to set a positional range based on two sliders:

ps =
    params
        << param "xMin"
            [ paValue (num 0)
            , paBind (ipRange [ inMin 0, inMax 400 ])
            ]
        << param "xMax"
            [ paValue (num 400)
            , paBind (ipRange [ inMin 0, inMax 400 ])
            ]


enc =
    encoding
        << position X
            [ pName "x"
            , pScale [ scRange (raExprs [ "xMin", "xMax" ]) ]
            ]
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.

raMin : Float -> ScaleRange

Set the minimum value of a continuous numeric range. To set both the min and max values use raNums.

raMax : Float -> ScaleRange

Set the maximum value of a continuous numeric range. To set both the min and max values use raNums.

raNumLists : List (List Float) -> ScaleRange

Scale range comprising numeric lists. Useful, for example, when defining custom dash styles for a strokeDash channel encoding.

raStrs : List String -> ScaleRange

Text scale range for discrete scales.

raField : String -> ScaleRange

Specify the field that contains explicit range values. This should be a one-to-one match with the field of domain values. Can be used, for example, to set color values explicitly from a data source.

5.10.3 Scaling Properties

scScheme : String -> List Float -> ScaleProperty

Color scheme used by a color scaling with mScale. The first parameter is the name of the scheme (e.g. "viridis"). For a full list of supported color scheme names, see the Vega documentation. The second parameter is 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).

color
    [ mName "value"
    , mOrdinal
    , mScale [ scScheme "redblue" [ 0, 0.8 ] ]
    ]
scSchemeExpr : String -> List Float -> ScaleProperty

Expression that evaluates to a color scheme for color scaling. The first parameter is the expression and the second as for scScheme. For example, to choose from a pair of preset schemes:

ps =
    params
        << param "clrs"
            [ paValue (str "plasma")
            , paBind (ipSelect [ inOptions [ "plasma", "oranges" ] ])
            ]


enc =
    encoding
        << color [ mName "val", mScale [ scSchemeExpr "clrs" [] ] ]

Can be used to specify a custom interpolated colour scheme by providing a list of colours as a parameter value:

ps =
    params
        << param "myScheme" [ paValues (strs [ "blue", "white", "red" ]) ]


enc =
    encoding
        << color [ mName "val", mScale [ scSchemeExpr "myScheme" [] ] ]

Alignment of the steps within the scale range. Parameter is capped between 0 and 1 where 0.5 indicates steps are centred within range, 0 shifts bands to an axis, 1 away from axis.

Padding in pixels to apply to a scaling.

Inner padding to apply to a band scaling.

Outer padding to apply to a band scaling.

Whether or not to reverse sorting order of a scaling.

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.

A 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. If data to be scaled contain zeros or negative values, consider scSymLog instead.

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.

A square root scale.

A threshold scale.

A temporal scale.

A UTC temporal scale.

Scaling Constants

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.

niExpr : String -> ScaleNice

Specify nice scaling with an expression that evaluates to a valid nice property (e.g. a number or time interval)

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


6. View Composition

Views can be combined to create more complex multi-view 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. For example, adding text annotations to a bar chart:

let
    data =
        dataFromColumns []
            << dataColumn "x" (nums [ 1, 2, 3, 4, 5 ])
            << dataColumn "a" (nums [ 28, 91, 43, 55, 81 ])


    enc =
        encoding
            << position X [ pName "x", pOrdinal ]
            << position Y [ pName "a", pQuant ]
            << text [ tName "a", tNominal ]
in
toVegaLite
    [ data []
    , enc []
    , layer
        [ asSpec [ bar [] ]
        , asSpec [ textMark [ maDy -8 ], enc [] ]
        ]
    ]
concat : List Spec -> ( VLProperty, Spec )

Specifications to be juxtaposed in a flow layout of views. The number of columns in the flow layout can be set with columns and if not specified will default to a single row of unlimited columns.

let
    data =
        dataSequenceAs 0 6.28 0.1 "x"


    trans =
        transform
            << calculateAs "sin(datum.x)" "sinX"
            << calculateAs "cos(datum.x)" "cosX"


    enc =
        encoding
            << position X [ pName "x", pQuant ]


    encCos =
        enc << position Y [ pName "cosX", pQuant ]


    encSin =
        enc << position Y [ pName "sinX", pQuant ]
in
toVegaLite
    [ data
    , trans []
    , concat
        [ asSpec [ encCos [], line [] ]
        , asSpec [ encSin [], line [] ]
        ]
    ]
columns : 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 0, negative 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 )

Juxtapose some specifications 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.

6.1 Resolution

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

resolve : List LabelledSpec -> ( VLProperty, Spec )

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

let
    data =
        dataFromColumns []
            << dataColumn "x" (nums [ 1, 2, 3, 4, 5 ])
            << dataColumn "a" (nums [ 28, 91, 43, 55, 81 ])
            << dataColumn "b" (nums [ 17, 22, 28, 30, 40 ])


    encBar =
        encoding
            << position X [ pName "x", pQuant ]
            << position Y [ pName "a", pQuant ]


    specBar =
        asSpec [ bar [], encBar [] ]


    encLine =
        encoding
            << position X [ pName "x", pQuant ]
            << position Y [ pName "b", pQuant ]


    specLine =
        asSpec [ line [ maColor "firebrick" ], encLine [] ]


    res =
        resolve
            << resolution (reScale [ ( chY, reIndependent ) ])
in
toVegaLite [ data [], res [], layer [ specBar, specLine ] ]
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 ) ])

Channel should be shared with others in a composite visualization.

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

Reference to whatever is being encoded on the X channel. Can be used in the projection of interactive selections or in a resolution specification.

Reference to whatever is being encoded on the Y channel. Can be used in the projection of interactive selections or in a resolution specification.

Reference to whatever is being encoded on the X2 channel. Can be used in a resolution specification.

Reference to whatever is being encoded on the Y2 channel. Can be used in a resolution specification.

Reference to whatever is being encoded on the XOffset channel. Can be used in a resolution specification.

Reference to whatever is being encoded on the Y offset channel. Can be used in a resolution specification.

Reference to whatever is being encoded on the color channel. Can be used in the projection of interactive selections or in a resolution specification.

Reference to whatever is being encoded on the opacity channel. Can be used in the projection of interactive selections or in a resolution specification.

Reference to whatever is being encoded on the shape channel. Can be used in the projection of interactive selections or in a resolution specification.

Reference to whatever is being encoded on the size channel. Can be used in the projection of interactive selections or in a resolution specification.

Reference to whatever is being encoded on the stroke dash channel. Can be used in the projection of interactive selections or in a resolution specification.

6.2 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 make a composite view from multiple fields. Similar to repeatFlow except that the fields for repetition are explicitly allocated to rows, columns or layers.

Unlike faceting, which creates multiple charts based on different values of a single field, repeating uses a different field for each chart.

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.

layerFields : List String -> RepeatFields

Create a list of fields to use in set of repeated layers. The list of fields named here can be referenced in an encoding with pRepeat layer, mRepeat layer 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", fNominal ]
    , 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", fOrdinal ]
            , columnBy [ fName "week", fOrdinal ]
            ]
    , 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

Name of field used for encoding with a facet channel.

Indicate a data field encoded as a facet property is nominal. This is the default data type.

Indicate a data field encoded as a facet property is ordinal.

Indicate a data field encoded as a facet property is quantitative.

Indicate a data field encoded as a facet property is temporal.

Indicate a data field encoded as a facet property is a geo feature.

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.

row
    [ fName "site"
    , fOrdinal
    , 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.

Alignment to apply to a rows or columns in a facet's sub-plot.

Whether or not a facet's sub-plots should be centred relative to their respective rows or columns.

Spacing in pixels between sub-views in a faceted view.

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", fNominal ] ]
    , specification spec
    ]

Layer arrangement in a repeated view.

Flow arrangement in a repeated/faceted view.

Column arrangement in a repeated/faceted view.

Row arrangement in a repeated/faceted view.

6.2.1 Facet Headers

See Vega-Lite header documentation

hdNumExpr : String -> (number -> HeaderProperty) -> HeaderProperty

Provide an expression to a facet header property function requiring a numeric value. This can be used for interactive parameterisation when an expression is bound to an input element. For example,

ps =
    params
        << param "size"
            [ paValue (num 12)
            , paBind (ipRange [ inMax 32 ])
            ]


enc =
    encoding
        << column
            [ fName "country"
            , fHeader [ hdNumExpr "size" hdLabelFontSize ]
            ]
hdStrExpr : String -> (String -> HeaderProperty) -> HeaderProperty

Provide an expression to a facet header property function requiring a string value. This can be used to provide an interactive parameterisation of a header property when an expression is bound to an input element. For example,

ps =
    params
        << param "color"
            [ paValue (str "black")
            , paBind (ipColor [])
            ]


enc =
    encoding
        << column
            [ fName "country"
            , fHeader [ hdStrExpr "color" hdLabelColor ]
            ]

Header Labels

Header label rotation angle (in degrees from horizontal) 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.

Vertical alignment of header labels.

Header label text color for a faceted view.

Expression for customising header labels. Can reference datum.value and datum.label for access to the underlying data values and label text respectively.

Header label font in a faceted view.

Header label font size in a faceted view.

Header label font style (e.g. italic) in a faceted view.

Header label font weight in a faceted view.

Maximum length of a header label in a faceted view.

Header label line height in a faceted view (useful for multi-line labels).

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.

Whether or not labels in a faceted view are displayed.

Header Title

Header title in a faceted view. A 'title' is the overall title describing the collection of faceted plots. For multi-line titles, insert \n at each line break or use a """ multi-line string.

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 (degrees from horizontal).

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.

Header title font style (e.g. italic) in a faceted view.

Title font size in a faceted view.

Title font weight in a faceted view.

Maximum length of a header title in a faceted view.

Header title line height in a faceted view (useful for multi-line titles).

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

The relative position of both a header label and title relative to a sub-plot (shortcut instead of specifying hdLabelOrient and hdTitleOrient separately).

Spacing in pixels between the main facet title and labels.

Header Formatting

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

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.

Indicate that facet headers should be formatted with a registered custom formatter with the given name. See how to register a Vega-Lite custom formatter.


7. Parameters

Vega-Lite parameters allow named objects whose values can change to persist within a specification. In the case of simple variables, it is often easier to use Elm directly to store persistent values. The main benefits of parameters are for storing interaction selections such as mouse selections or slider values. See the Vega-Lite parameter documentation for details.

params : List LabelledSpec -> ( VLProperty, Spec )

Specify top-level parameters to be used within a specification. While literals may be specified as parameters, these are better handled directly in Elm. More useful expression parameters are those that use the vega-lite built-in parameters width, height, padding, autosize, background and cursor. For example to keep text size a fixed proportion of the plot height:

ps =
    params
        << param "textSize" [ paExpr "height/20" ]

Also useful is the ability to bind parameters to input elements such as range sliders that may be updated at runtime. For example the value of the radius parameter is determined by the slider position and then used as a mark property to alter circle size dynamically:

let
    ps =
        params
            << param "radius"
                [ paValue (num 0)
                , paBind (ipRange [ inMax 100 ])
                ]


    enc =
        encoding
            << position Theta [ pName "value", pQuant ]
            << color [ mName "category" ]
in
toVegaLite
    [ ps []
    , data []
    , enc []
    , arc [ maNumExpr "radius" maInnerRadius ]
    ]
String
-> List ParamProperty
-> List LabelledSpec
-> List LabelledSpec

Add a named parameter to a list of parameters. A parameter should have a name and a list of parameter details. For example,

param "mySelection" [ paSelect seInterval [] ]

Provide an initial value of a parameter. This can be useful, for example, when setting the initial value of an interaction parameter:

ps =
    params
        << param "quarterSelection"
            [ paValue (num 3)
            , paSelect sePoint [ seFields [ "quarter" ] ]
            , paBind (ipRange [ inMin 1, inMax 4, inStep 1 ])
            ]

If the value of a selection parameter needs to be explicitly referenced, such as in a data filtering operation, the parameter value can be initialised with a named tuple. For example to filter data between two interactive slider values:

ps =
    params
        << param "minSlider"
            [ paSelect sePoint []
            , paValue (dataObject [ ( "minVal", num 0 ) ])
            , paBind (ipRange [ inMin 0, inMax 50 ])
            ]
        << param "maxSlider"
            [ paSelect sePoint []
            , paValue (dataObject [ ( "maxVal", num 100 ) ])
            , paBind (ipRange [ inMin 50, inMax 100 ])
            ]


trans =
    transform
        << filter (fiExpr "datum.x >= minSlider_minVal && maxSlider_maxVal >= datum.x")

Initial set of values of a parameter. Useful for passing to functions that require a list of values. For example, to allow filtering by two separate data values:

ps =
    params
        << param "CylYr"
            [ paSelect sePoint [ seFields [ "Cylinders", "Year" ] ]
            , paValues (dataObjects [ [ ( "Cylinders", num 4 ), ( "Year", num 1977 ) ] ])
            , paBindings
                [ ( "Cylinders", ipRange [ inMin 3, inMax 8, inStep 1 ] )
                , ( "Year", ipRange [ inMin 1969, inMax 1981, inStep 1 ] )
                ]
            ]
paExpr : String -> ParamProperty

Initial value of a parameter specified as a Vega expression. For example:

ps =
    params
        << param "cx" [ paExpr "width/2" ]
        << param "cy" [ paExpr "height/2" ]

7.1 Selection Parameters

Specify a selection parameter to be used for interaction. For example, to create an interval selection:

param "mySelection" [ paSelect seInterval [] ]

To project a point selection across the field encoded with colour:

param "mySelection" [ paSelect sePoint [ seEncodings [ chColor ] ] ]

Specify a point selection type.

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

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

ps =
    params
        << param "myZoomPan"
            [ paSelect seInterval [ seClear "click[event.shiftKey]" ]
            , paBindScales
            ]

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

Encoding channels that form a named selection. For example, to project a selection across all items that share the same value in the color channel:

ps =
    params
        << param "sel" [ paSelect sePoint [ seEncodings [ chColor ] ] ]
seFields : List String -> SelectionProperty

Field names for projecting a selection over multiple fields.

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. For example, to create a paintbrush effect under the pointer:

ps =
    params
        << param "paint" [ paSelect sePoint [ seOn "mouseover" ] ]

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

For example, to create a paintbrush type effect that leaves a trail of selections under the pointer while the shift key is pressed down:

ps =
    params
        << param "paint"
            [ paSelect sePoint [ seOn "mouseover", seToggle tpShiftKey ] ]

Specify that data values in a selection are never unselected when interacted with on multiple occasions. This allows a single selected item to be guaranteed.

Specify that repeated selections are toggled when the given expression evaluates to true. This allows, for example, multiple key modifiers to generate toggling:

ps =
    params
        << param "paint"
            [ paSelect sePoint
                [ seOn "mouseover"
                , seToggle (tpExpr "event.shiftKey && event.ctrlKey")
                ]
            ]

Specify that data values in a selection are toggled when interacted with on multiple occasions while the shift key is held down. This is the default behaviour so should only be needed if moving back from some other specified behavior.

Specify that data values in a selection are toggled when interacted with on multiple occasions while the alt key is held down.

Specify that data values in a selection are toggled when interacted with on multiple occasions while the control key is held down.

Interaction event stream for translating an interval selection. If an empty string, selection translation will be disabled. See the Vega-Lite zoom documentation

Interaction event stream for zooming an interval selection. If an empty string, zooming will be disabled. See the Vega-Lite zoom documentation

Selection Bindings

The dynamic binding associated with a parameter. Can be used to create a parameter value that varies as an interactive input control (e.g. slider) is updated. For details see the Vega-Lite binding documentation

param "mySlider"
    [ paSelect sePoint []
    , paBind (ipRange [ inMin 1, inMax 10 ])
    ]
paBindings : List ( String, PBinding ) -> ParamProperty

One or more named dynamic bindings associated with a parameter. Unlike paBind, this allows multiple input elements to be bound to the same field. For example, to bind a selection to the 'And' selection of two sliders:

param "CylYr"
    [ paSelect sePoint [ seFields [ "Cylinders", "Year" ] ]
    , paBindings
        [ ( "Cylinders", ipRange [ inMin 3, inMax 8, inStep 1 ] )
        , ( "Year", ipRange [ inMin 1969, inMax 1981, inStep 1 ] )
        ]
    ]

Bind a named parameter selection to the scales of a view to allow interactive zooming and panning. For example,

ps =
    params
        << param "zoomer" [ paSelect seInterval [], paBindScales ]

Bind a named parameter selection to a legend for interactive selection of field values from a legend. Can be bound to a field or channel. For example the following will bind a color legend to a point selection allowing filtering or highlighting by the selected value that has been encoded with color.

ps =
    params
        << param "legSel"
            [ paSelect sePoint [ seEncodings [ chColor ] ]
            , paBindLegend ""
            ]

To customise which events should trigger legend interaction, provide a Vega event stream string. If an empty string is provided, the default single-click interaction is used.

For example, to allow legend selection with a double click:

paBindLegend "dblClick"

or with shift-click:

paBindLegend "click[event.shiftKey]"

Input Elements

Range slider input element that can bound to a named parameter.

Checkbox input element that can bound to a named parameter.

Radio box input element that can bound to a named parameter.

Select input element that can bound to a named parameter.

Text input element that can bound to a named parameter.

Number input element that can bound to a named parameter.

Date input element that can bound to a named parameter.

Time input element that can bound to a named parameter.

Month input element that can bound to a named parameter.

Week input element that can bound to a named parameter.

Local time input element that can bound to a named parameter.

Telephone number input element that can bound to a named parameter.

Color input element that can bound to a named parameter.

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. Assumes all options are strings. For other types, consider inDatumOptions or inDataOptions.

Options for a radio or select input element. Unlike inOptions, this allows for mixed data types to be listed. For example, to create a list of numbers and boolean values:

inDatumOptions [ num 2, num 3, boo False, boo True ]

Options for a radio or select input element. Similar to inDatumOptions except that each option can be a list of data values. For example,

inDataOptions [ nums [ 2, 3, 5, 7, 11, 13 ], boos [ True, False ] ]
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.

### Selection Marks

Customising the appearance of interval selection rectangles.

Appearance of an interval selection mark (dragged rectangle).

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.

Cursor type to appear when pointer is over an interval selection mark (dragged rectangular area).

7.2 Selection Resolution

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

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

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.

7.3 Conditional Channel Encodings

Channel encoding can be made conditional on a parameter value, therefore allowing it to be the result of some interaction or data expression. It does this via mCondition (and its 'o', 't' and 'h' variants). Mark appearance can therefore depend on some properties such as whether a datum is null or whether it has been interactively selected. The condition to test (predicate) is usually specified either as a parameter with prParam or an expression with prTest.

Make a mark channel encoding conditional on a predicate expression. A predicate might be the result of evaluating a parameter (prParam) or an expression (prTest). The first parameter is the predicate that evaluates to true or false; the second the encoding if true, the third the encoding if false. For example, to encode in one of two colours depending on a selection:

encoding
    << color
        [ mCondition (prParam "mySelection")
            [ mStr "red" ]
            [ mStr "black" ]
        ]

Make a mark channel conditional on a sequence of predicate values. This can be used when several predicates need to be tested in sequence each with their own encoding outcome ('if-else'). For example a four-way conditional color encoding can be specified as:

encoding
    << color
        [ mConditions
            [ ( prTest (expr "datum.value < 40"), [ mStr "blue" ] )
            , ( prTest (expr "datum.value < 50"), [ mStr "red" ] )
            , ( prTest (expr "datum.value < 60"), [ mStr "yellow" ] )
            ]
            [ mStr "black" ]
        ]

Make an order channel encoding conditional on a predicate expression. A predicate might be the result of evaluating a parameter (prParam) or an expression (prTest). The first parameter is the predicate that evaluates to true or false; the second the encoding if true, the third the encoding if false.

For example, to bring marks of an interactively selected colour to the front:

ps =
    params
        << param "sel" [ paSelect sePoint [ seEncodings [ chColor ] ] ]


enc =
    encoding
        << order [ oCondition (prParam "sel") [ oNum 1 ] [ oNum 0 ] ]

Make an order channel conditional on a sequence of predicate values. This can be used when several predicates need to be tested in sequence each with their own encoding outcomes ('if-else'). For example to control mark z-order for three category values:

order
    [ oConditions
        [ ( prTest (expr "datum.Origin == 'Europe'"), [ oNum 3 ] )
        , ( prTest (expr "datum.Origin == 'Japan'"), [ oNum 2 ] )
        ]
        [ oNum 1 ]
    ]

Make a text channel encoding conditional on a predicate expression. A predicate might be the result of evaluating a parameter (prParam) or an expression (prTest). The first parameter is the predicate that evaluates to true or false; the second the encoding if true, the third the encoding if false.

Make an text channel conditional on a sequence of predicate values. This can be used when several predicates need to be tested in sequence each with their own encoding outcomes ('if-else').

Make a hyperlink channel encoding conditional on a predicate expression. A predicate might be the result of evaluating a parameter (prParam) or an expression (prTest). The first parameter is the predicate that evaluates to true or false; the second the encoding if true, the third the encoding if false.

prParam : String -> Predicate

Parameter name that should evaluate to either true or false for use in functions that use predicates, such as mCondition.

Parameter name that should evaluate to either true or false for use in selections for conditional encoding. Same as prParam except that an empty selection is assumed to be false.

Test that should evaluate to either true or false for use in functions that use predicates, such as mCondition

bParam : String -> BooleanOp

Treat a parameter as a boolean expression that may be composed to form more complex boolean expressions. Can be used when composing selections from multiple parameters. For example, if we have two interval selection parameters alex and morgan we can conditionally colour if both selections intersect.

color
    [ mCondition (prTest (and (bParam "alex") (bParam "morgan")))
        [ mStr "red" ]
        [ mStr "gray" ]
    ]
expr : String -> BooleanOp

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

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

8. Top-Level Settings

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.

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. How the content is sized relative to this height specification can be customised with autosize.

Set the height of the view to be that of the surrounding container. Allows responsive sizing to be specified.

width : Float -> ( VLProperty, Spec )

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

toVegaLite [ width 540, data [], enc [], bar [] ]

How the content is sized relative to this width specification can be customised with autosize.

Set the width of the view to be that of the surrounding container. Allows responsive sizing to be specified.

widthStep : Float -> ( VLProperty, Spec )

Set the width of the discrete x-field (e.g. individual bars in a bar chart). The total width is then calculated based on the number of discrete fields (e.g. bars).

toVegaLite [ widthStep 17, data [], enc [], bar [] ]
widthStepOffset : Float -> ( VLProperty, Spec )

Set the width of the offset-grouped discrete x-fields. The total width is then calculated based on the number of offset discrete fields (e.g. groups of bars with position XOffset applied).

heightStep : Float -> ( VLProperty, Spec )

Set the height of the discrete y-field (e.g. individual bars in a horizontal bar chart). The total height is then calculated based on the number of discrete fields (e.g. bars).

toVegaLite [ heightStep 17, data [], enc [], bar [] ]
heightStepOffset : Float -> ( VLProperty, Spec )

Set the height of the offset-grouped discrete y-fields. The total height is then calculated based on the number of offset discrete fields (e.g. groups of bars with position YOffset applied).

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.

paNumExpr : String -> (number -> Padding) -> Padding

Provide an expression to a padding property function requiring a numeric value such as paSize.

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.

paEdgesExpr : String -> String -> String -> String -> Padding

Expressions that each evaluate to a numeric values indicating padding around a visualization in pixel units. The four parameters refer to left, top, right and bottom edges respectively. Can be useful when padding is to be determined interactively through input elements.

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

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

Interpret visualization height to be for the entire visualization height (data rectangle height 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 white.

backgroundExpr : String -> ( VLProperty, Spec )

Expression that evaluates to a colour used for the visualization background. Useful when the colour is to be determined at runtime though an interaction element such as ipColor.

userMeta : List ( String, DataValue ) -> ( VLProperty, Spec )

Add custom metadata to a specification. While these are ignored by Vega-Lite, this can be useful for cusstom implementations that require addtional metadata. The parameter should be a series of named key-value pairs that will be stored in the specification as a JavaScript object. For example,

userMeta
    [ ( "Custom1", num 13 )
    , ( "Custom2", str "hello" )
    , ( "Custom3", datumArray ([ 1, 2, 3, 4 ] |> List.map num) )
    , ( "Custom4", dataObject [ ( "nested1", num 14 ), ( "nested2", boo True ) ] )
    , ( "Custom5", nullValue )
    ]

8.1 Title

Per-title settings. To standardize the appearance of all titles in a multi-view specification, use coTitle instead.

tiNumExpr : String -> (number -> TitleProperty) -> TitleProperty

Provide an expression to a title property function requiring a numeric value. This can be used for interactive parameterisation when an expression is bound to an input element. For example,

ps =
    params
        << param "fs"
            [ paValue (num 0)
            , paBind (ipRange [ inMax 32 ])
            ]


ttl =
    title "My title" [ tiNumExpr "fs" tiFontSize ]
ticoNumExpr : String -> (number -> TitleConfig) -> TitleConfig

Provide an expression to a title configuration function requiring a numeric value.

tiStrExpr : String -> (String -> TitleProperty) -> TitleProperty

Provide an expression to a title property function requiring a string value. This can be used to provide an interactive parameterisation of a title property when an expression is bound to an input element. For example,

ps =
    params
        << params "clr"
            [ paValue (str "black")
            , paBind (ipColor [])
            ]


ttl =
    title "My title" [ tiStrExpr "clr" tiColor ]
ticoStrExpr : String -> (String -> TitleConfig) -> TitleConfig

Provide an expression to a title configuration function requiring a string value.

title : String -> List TitleProperty -> ( VLProperty, Spec )

Title to be displayed for a plot. The first parameter is the text of the title, the second a list of any title properties to configure its appearance. To display a title over more than one line, insert \n at each line break or use a """ multi-line string.

title "First line\nSecond line" []

or

title """First line
Second line""" []
titleExpr : String -> List TitleProperty -> ( VLProperty, Spec )

Expression that evaluates to a title. Similar to title except the content of the title is the evaluated expression (first parameter). For example:

let
    ps =
        params << param "ttl" [ paValue (num (2 * pi)) ]
in
toVegaLite [ titleExpr "ttl" [] ]

Anchor position when placing a title.

Angle of title text (degrees from horizontal).

Vertical alignment of a title.

Text colour of a title.

tiDx : Float -> TitleProperty

Delta offset of title and subtitle x-position.

tiDy : Float -> TitleProperty

Delta offset of title and subtitle y-position.

tiFont : String -> TitleProperty

Title font.

Title font size.

Title font style (italic etc.).

Title font weight.

Line height (vertical spacing) for title text.

Subtitle text, placed beneath the primary title. For multi-line subtitles, insert \n at each line break or use a """ multi-line string.

Color of a subtitle.

Font name of a subtitle.

Font size of a subtitle.

Font style of a subtitle such as "normal" or "italic".

Font weight of a subtitle.

Line height in pixels of each line of text in a multi-line subtitle.

Padding in pixels between title and subtitle text.

Title position anchor. Can be relative to the full bounding box (frBounds) or the group in which the titled visualization belongs (frGroup).

Specify a title anchor position relative to the full bounding box.

Specify a title anchor position relative to the group width / height.

tfExpr : String -> TitleFrame

Specify a title anchor position as an expression that should evaluate to one of "bounds" or "frame".

Maximum length of the title display in pixel units.

Offset in pixel units of the title relative to the chart body.

Placement of title relative to the chart body.

tiStyle : List String -> TitleProperty

A list of named styles to apply to title. A named style can be specified via coMarkStyles 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.

While this is provided for compatibility with Vega-Lite style specification, for greater type safety in elm-vegalite, instead create functions that generate TitleProperties.

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

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

vbNumExpr : String -> (number -> ViewBackground) -> ViewBackground

Provide an expression to a view background function requiring a numeric value. This can be used for interactive parameterisation when an expression is bound to an input element. For example,

ps =
    params
        << param "r"
            [ paValue (num 0)
            , paBind (ipRange [ inMax 20 ])
            ]


bg =
    viewBackground [ vbNumExpr "r" viewCornerRadius ]
vicoNumExpr : String -> (number -> ViewConfig) -> ViewConfig

Provide an expression to a view background confguration function requiring a numeric value.

vbNumsExpr : String -> (List number -> ViewBackground) -> ViewBackground

Provide an expression to a view background function requiring a list of numbers (for dash styles). This can be used to provide an interactive parameterisation of a view background dash property when an expression is bound to an input element. For example,

ps =
    params
        << param "dashStyle"
            [ paValue (nums [ 2, 2 ])
            , paBind (ipSelect [ inDataOptions [ nums [ 2, 2 ], nums [ 8, 8 ] ] ])
            ]


bg =
    viewBackground [ vbNumsExpr "dashStyle" viewStrokeDash ]
vicoNumsExpr : String -> (List number -> ViewConfig) -> ViewConfig

Provide an expression to a view background configuration function requiring a list of numbers (for dash styles).

vbStrExpr : String -> (Maybe String -> ViewBackground) -> ViewBackground

Provide an expression to a view background function requiring a Maybe String value. This can be used to provide an interactive parameterisation of a view background when an expression is bound to an input element. For example,

ps =
    params
        << param "clr"
            [ paValue (str "white")
            , paBind (ipColor [])
            ]


bg =
    viewBackground [ vbStrExpr "clr" viewFill ]
vicoStrExpr : String -> (Maybe String -> ViewConfig) -> ViewConfig

Provide an expression to a view background configuration function requiring a Maybe String value.

vicoBooExpr : String -> (Bool -> ViewConfig) -> ViewConfig

Provide an expression to a view configuration function a Boolean value.

viewStyle : List String -> ViewBackground

A list of named styles to apply to a single view background. A named style can be specified via coMarkStyles 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.

8.3 Configuration of Default Appearance

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. Each configuration that makes up the global list of customisations refers to a specific part of all visualizations to which it is applied, such as axes, legends, selections etc. See the Vega-Lite documentation.

Individual configuration functions are prefixed with an abbreviation of the part of the visualization to configure followed by co. For example, axis configuration functions axco, legends leco, titles tico, faceting faco etc.

The following makes all axis lines (domain) 2 pixels wide, removes the border rectangle and requires interactive selection of items to use a double-click.

let
    cfg =
        configure
            << configuration (coAxis [ axcoDomainWidth 2 ])
            << configuration (coView [ vicoStroke Nothing ])
            << configuration (coSelection [ ( sePoint, [ seOn "dblclick" ] ) ])
in
toVegaLite [ cfg [], data [], enc [], bar [] ]
configuration : ConfigurationProperty -> List LabelledSpec -> List LabelledSpec

A configuration option to be applied globally across the visualization.

Provide an expression to a top-level configuration function requiring a Boolean value. This can be used to provide an interactive parameterisation when an expression is bound to an input element.

Provide an expression to a top-level configuration function requiring a string value. This can be used to provide an interactive parameterisation when an expression is bound to an input element.

Configure the default appearance of area marks.

Whether or not ARIA attributes should be included for marks and guides when generating SVG output. If not specified, the default is True.

Configure the default sizing of visualizations.

Configure the default appearance of axes.

Filter an axis configuration so that it only applies to x-axes. For example, to configure all band X-axes to be red:

configuration (coAxisBand [ axcoTitleColor "red" ] |> coAxisXFilter)

Filter an axis configuration so that it only applies to y-axes. For example, to configure all temporal Y-axes to be red:

configuration (coAxisTemporal [ axcoTitleColor "red" ] |> coAxisYFilter)

Indicate configuration should be applied to the x-axis only.

Indicate configuration should be applied to the y-axis only.

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 any axes using a band (binned) scale.

Configure the default appearance of any axes using a discrete scale.

Configure the default appearance of any axes using a point scale.

Configure the default appearance of any quantitative axes.

Configure the default appearance of any temporal axes.

Specify a list of named styles that each define a list of axis properties. Provided for compatibility with Vega-Lite, but generally greater type safety is achieved in elm-vegalite by creating elm functions that generate lists of AxisProperties.

Configure the default background color of visualizations.

Configure the default appearance of bar marks.

Configure the default appearance of circle marks.

Configure the default appearance of concatenated layouts.

Configure the default title style for count fields.

Determine whether formatting of text marks and guides (e.g. axFormatAsCustom) will accept a custom formatter function. If true, the custom formatter should be registered as a Vega expression. For example, registering the JavaScript function

vega.expressionFunction('unitFormat', function (datum, params) {
  const dp = params.match(/\d+/)[0];
  const unit = params.replace(dp, '');
  return datum.toFixed(dp) + unit;
});

And enabling custom formatting within

cfg =
    configure
        << configuration (coCustomFormatTypes True)

Allows custom axis formatting such as the following to display units to 2 decimal places followed by an 'm'

pAxis
    [ axTitle "Flipper length"
    , axFormatAsCustom "unitFormat"
    , axFormat "2m"
    ]

See how to register a Vega-Lite custom formatter.

Configure the default title generation style for fields.

Configure the default font for all titles, labels and text marks.

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.

coLocale : List LocaleProperty -> ConfigurationProperty

Specify the default locale settings. Allows, for example, local currency, time and thousands separators to be defined as the default. For example a German locale might be defined as

coLocale
    [ loDecimal ","
    , loThousands "."
    , loGrouping 3
    , loCurrency "" "\\u00a0€"
    ]

Configure the default mark appearance.

Specify a list of named styles that each define a list of mark properties. Can be used when configuring views, titles etc. Provided for compatibility with Vega-Lite, but generally greater type safety is achieved in elm-vegalite by creating elm functions that generate lists of MarkProperties.

Configure the default number formatting for numeric output that appears in axis labels, legends and tooltips. Uses d3 format codes to set appearance of numbers. For example, to display numeric values to 3 decimal places:

cfg =
    configure
        << configuration (coNumberFormat ".3f")

Provide the name of a registered custom formatter for numeric output that appears in axis labels, legends and tooltips. See coCustomFormatTypes for an example of how to register custom formatter.

Configure the default number formatting for normalized numeric output used by stacked charts. Uses d3 format codes to set appearance of numbers.

Provide the name of a registered custom formatter for numeric output used by stacked charts. See coCustomFormatTypes for an example of how to register custom formatter.

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 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 appearance of text marks.

Configure the default appearance of tick marks.

coTitle : List TitleConfig -> ConfigurationProperty

Configure the default style of visualization titles.

Configure the default time format for axis and legend labels.

Provide the name of a registered custom formatter for temporal output that appears in axis labels, legends and tooltips. See coCustomFormatTypes for an example of how to register custom formatter.

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

Configure the default style of trail marks.

Configure the default single view style.

8.3.1 Axis Configuration

See the Vega-Lite axis config documentation.

Default ARIA properties for providing accessible SVG output associated with an axis. If an empty list is provided, ARIA tagging will be switched off.

Default axis band position.

Whether or not axes are generated for positional encoding by default.

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

axcoDomainDash : List Float -> AxisConfig

Default dash style of axis baseline (domain). The parameter should list number of pixels in alternating dash and gap lengths.

Default number of pixels before the first axis baseline (domain) line dash is drawn.

Default appearance of ends of axis domain.

Default axis domain color.

Default axis domain opacity.

Default axis domain width style.

Default maximum extent style.

Default minimum extent style.

Default coordinate space translation offset for axis layout.

Whether or not an axis grid is displayed by default.

Default appearance of ends of grid lines.

Default axis grid color style.

axcoGridDash : List Float -> AxisConfig

Default axis line dash style.

Default number of pixels before the first axis grid line dash is drawn.

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 (degrees from horizontal).

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.

Expression that evaluates to True, False or a number depending whether, by default, a check is to be made for an axis label size. A number specifies the permitted overflow in pixels.

Default axis label color.

Default expression to generate axis labels. The parameter is a valid Vega expression. Can reference datum.value and datum.label for access to the underlying data values and default label text respectively.

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.

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

Default axis label font.

Default axis label font size.

Default axis label font style (e.g. "italic")

Default axis label font weight.

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

Default axis label line height (useful for multi-line labels).

Default axis offset in pixels of an axis's labels relative to its ticks.

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

Default axis label separation (minimum spacing between axis labels).

Default offset between the axis and the edge of the enclosing group or data rectangle.

axcoStyle : List String -> AxisConfig

A list of named styles to apply as defaults to axes.

Whether or not an axis should show ticks by default.

axcoTickBand : TickBand -> AxisConfig

Default alignment of grid lines and ticks in band scales.

Default axis tick end cap style.

Default axis tick mark color.

Default number of, or interval between, axis ticks. The resulting number of ticks may be different so that values are “nice” (multiples of 2, 5, 10).

axcoTickDash : List Float -> AxisConfig

Default axis tick dash style. The parameter is a list of alternating 'on' and 'off' lengths in pixels representing the dashed line.

Default number of pixels before the first axis tick dash is drawn.

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.

Default axis tick mark width.

Default axis tick label horizontal alignment.

Default anchor position of axis titles.

Default axis title angle (degrees from horizontal).

Default axis title vertical alignment.

Default axis title color.

Default axis title font.

Default axis title font size.

Default axis title font style (e.g. "italic").

Default axis title font weight.

Default axis title maximum size.

Default line height for multi-line axis titles.

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.

8.3.2 Legend Configuration

See the Vega-Lite legend configuration documentation.

Default ARIA properties for providing accessible SVG output associated with a legend. If an empty list is provided, ARIA tagging will be switched off.

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 direction of a legend.

Whether or not legends should be disabled by default.

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 maximum allowable length for labels in a color ramp legend.

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

Default length in pixels of the primary axis of a color ramp legend.

Default opacity of a color ramp legend.

Default color for strokes in a color ramp legend.

Default width for strokes in a color ramp legend.

Default thickness in pixels of a color ramp legend.

Default 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 of legend labels.

Default font style (italic etc.) of legend labels.

Default font weight of legend labels.

Default maximum width for legend labels in pixel units.

Default offset for legend labels.

Strategy for resolving overlapping legend labels.

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 legend symbol dash style in legend encoding.

Default legend symbol dash offset in legend encoding.

Default direction of a symbol legend.

Default legend symbol fill color.

Default legend symbol fill color.

Default horizontal pixel offset for legend symbols.

Default legend symbol opacity.

Default legend symbol size.

Default legend symbol outline color.

Default legend symbol stroke width.

Default legend symbol type.

Default to not displaying any legend titles.

Default horizontal alignment for legend titles.

Default anchoring 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 style (italic etc) for legend titles.

Default font weight for legend titles.

Default maximum size in pixel units for legend titles.

Default line height for multi-line legend titles.

Default opacity of a legend's title.

Default spacing in pixel units between title and legend.

Default opacity of unselected legend items when made interactive via seBindLegend.

lecoX : Float -> LegendConfig

Default x-position of legend group in pixel units for absolute positioning when leOrient is set to loNone.

lecoY : Float -> LegendConfig

Default y-position of legend group in pixel units for absolute positioning when leOrient is set to loNone.

8.3.3 Scale Configuration

See the Vega-Lite scale configuration documentation

sacoBooExpr : String -> (Bool -> ScaleConfig) -> ScaleConfig

Provide an expression to a scale property configuration function requiring a Boolean value.

sacoNumExpr : String -> (number -> ScaleConfig) -> ScaleConfig

Provide an expression to a scale property configuration function requiring a numeric value.

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

Default inner 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.

Default padding for continuous scales.

Default padding for point-ordinal scales.

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.

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

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

Whether or not to reverse the x-scaling by default (useful for right to left charts).

8.3.4 Scale Range Configuration

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 set of symbols for shape encoding.

Default set of symbols for shape encoding determined by the value of the given expression.

8.3.5 Title Configuration

Unlike title title configuration applies to all titles if multiple views are created. See the Vega-Lite title configuration documentation

ticoAnchor : Anchor -> TitleConfig

Default anchor position when placing titles.

ticoAngle : Float -> TitleConfig

Default angle when orientating titles (degrees from horizontal).

ticoBaseline : VAlign -> TitleConfig

Default vertical alignment when placing titles.

ticoColor : String -> TitleConfig

Default color when showing titles.

ticoDx : Float -> TitleConfig

Default delta offset of title and subtitle x-position.

ticoDy : Float -> TitleConfig

Default delta offset of title and subtitle y-position.

ticoFont : String -> TitleConfig

Default font when showing titles.

ticoFontSize : Float -> TitleConfig

Default font size when showing titles.

ticoFontStyle : String -> TitleConfig

Default font style (italic etc.) when showing titles.

ticoFontWeight : FontWeight -> TitleConfig

Default font weight when showing titles.

ticoLineHeight : Float -> TitleConfig

Line height (vertical spacing) for title text.

Default color of a subtitle.

ticoSubtitleFont : String -> TitleConfig

Default font name of a subtitle.

ticoSubtitleFontSize : Float -> TitleConfig

Default font size of a subtitle.

ticoSubtitleFontStyle : String -> TitleConfig

Default ont style of a subtitle such as "normal" or "italic".

Default font weight of a subtitle.

ticoSubtitleLineHeight : Float -> TitleConfig

Default line height in pixels of each line of text in a subtitle.

ticoSubtitlePadding : Float -> TitleConfig

Default padding in pixels between title and subtitle text.

ticoFrame : TitleFrame -> TitleConfig

Title position anchor. Can be relative to the full bounding box (frBounds) or the group in which the titled visualization belongs (frGroup).

ticoLimit : Float -> TitleConfig

Default maximum length in pixel units when showing titles.

ticoOffset : Float -> TitleConfig

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

ticoOrient : Side -> TitleConfig

Default placement of titles relative to the chart body.

ticoStyle : List String -> TitleConfig

A list of named styles to apply to titles. A named style can be specified via coMarkStyles 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.

ticoZIndex : Int -> TitleConfig

Default drawing order of titles relative to the other chart elements. 1 indicates titles are drawn in front of chart marks, 0 indicates they are drawn behind them.

8.3.6 View Configuration

See the Vega-Lite view configuration documentation

Configure the default single view style.

Default width of single views when the plot has continuous x-field.

Default height of single views when the plot has continuous y-field.

Default cursor for single views.

Default width of single views when the plot has discrete x-field.

Default height of single views when the plot has discrete y-field.

Whether or not by default single views should be clipped. Clipping will remove everything outside the data area including axes and legends.

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.

vicoStep : Float -> ViewConfig

Default step size for x/y discrete fields.

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.

anExpr : String -> Anchor

Specify an anchor style ("start", "middle", "end") with an expression.

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.

8.3.7 Facet Configuration

See the Vega-Lite facet configuration 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 faceted view.

8.3.8 Concatenated View Configuration

See the Vega-Lite concat configuration documentation.

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

Configuration option for the spacing in pixels between sub-views in a concatenated view.

8.3.9 Locale Configuration

See the Vega locale documentation.

loDecimal : String -> LocaleProperty

Symbol used to indicate decimal point as part of a locale specification.

loThousands : String -> LocaleProperty

Symbol used to indicate 'thousands' separator as part of a locale specification. Note that digits may be grouped in units other than thousands if loGrouping is set to a value other than 3.

loGrouping : Int -> LocaleProperty

Number of digits to represent what is by default a 'thousands' group, as part of a locale specification.

loCurrency : String -> String -> LocaleProperty

Indicate prefix (first parameter) and suffix (second parameter) currency symbols as part of a locale specification. For example

loCurrency "£" ""
loNumerals : List String -> LocaleProperty

List of 10 symbols to replace the numerals 0–9 as part of a locale specification.

loPercent : String -> LocaleProperty

Symbol used to indicate percentages as part of a locale specification.

loMinus : String -> LocaleProperty

Symbol used to indicate minus/negative as part of a locale specification.

loNan : String -> LocaleProperty

Symbol used to indicate a 'not-a-number' value, as part of a locale specification.

loDateTime : String -> LocaleProperty

Default format of date-time representation as part of a locale specification.. Uses d3-time-format symbols. For example,

loDatetime "%a %b %e %X %Y"
loDate : String -> LocaleProperty

Default format of date representation as part of a locale specification. Uses d3-time-format symbols. For example,

loDate "%_d %B %Y"
loTime : String -> LocaleProperty

Default format of time representation as part of a locale specification. Uses d3-time-format symbols. For example,

loTime "%I:%M %p"
loPeriods : String -> String -> LocaleProperty

Symbols used to indicate a time of day 'AM' (first parameter) and 'PM' (second parameter) equivalent, as part of a locale specification. For example,

loPeriods "a.m." "p.m."
loDays : List String -> LocaleProperty

List of the text representing the 7 days of the week (starting Sunday) as part of a locale specification.

loShortDays : List String -> LocaleProperty

List of the text representing the 7 abbreviated days of the week (starting Sunday) as part of a locale specification.

loMonths : List String -> LocaleProperty

List of the text representing the 12 months of the year (starting January) as part of a locale specification.

loShortMonths : List String -> LocaleProperty

List of the text representing the 12 abbreviated months of the year (starting January) as part of a locale specification.


9. General Data Functions

In addition to more general data types like integers and strings, the following types can carry data used in specifications and Vega-Lite parameters.

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.

datumExpr : String -> DataValue

A data value created by the given expression.

dataExpr : String -> DataValues

A list of data values created by the given expression.

List of data values. Unlike nums, strs etc., this allows a single array to store mixed types and nested values. For example,

datumArray [ num 10, str "a", datumArray [ num 99, boo False ] ]

Like datumArray except stores a collection of DataValues (like strs, nums) instead of singular datum items. This is just a convenience function for replicating a datumArray that contains lists of items of the same type. For example,

dataArrays [ nums [ 10, 20, 30 ], strs [ "a", "b", "c" ] ]

is equivalent to

datumArray
    [ datumArray [ num 10, num 20, num 30 ]
    , datumArray [ str "a", str "b", str "c" ]
    ]
dataObject : List ( String, DataValue ) -> DataValue

Key-value pairs representing a named data value. For example,

dataObject [ ( "x", num 3500 ), ( "firstName", str "Ada" ) ]
dataObjects : List (List ( String, DataValue )) -> DataValues

Generate a collection of lists of Key-value pairs representing named data values.

An unspecified data value. Can be useful when explicitly recoding a value as undefined.

data =
    dataFromRows []
        << dataRow [ ( "x", num 1 ), ( "y", num 10 ) ]
        << dataRow [ ( "x", num 2 ), ( "y", nullValue ) ]
        << dataRow [ ( "x", num 3 ), ( "y", num 30 ) ]

For more complex data sources that contain lists of defined and unspecified values, consider using dataFromJson instead.

Concatenate a list of data values as a single data value. For example,

param "location" [ paValue (daConcat (nums [ 4000, 8000 ])) ]
boos : List Bool -> DataValues

A list of Boolean data values. Used when declaring inline data with dataColumn, filtering (fiOneOf), imputation (imKeyVals) and customised sorting (soCustom).

dts : List (List DateTime) -> DataValues

List of date-time data values. Used when declaring inline data with dataColumn, filtering (fiOneOf), imputation (imKeyVals) and customised sorting (soCustom).

nums : List Float -> DataValues

List of numeric data values. Used when declaring inline data with dataColumn, filtering (fiOneOf), imputation (imKeyVals) and customised sorting (soCustom).

strs : List String -> DataValues

A list of string data values. Used when declaring inline data with dataColumn, filtering (fiOneOf), imputation (imKeyVals) and customised sorting (soCustom).

dtYear : Int -> DateTime

A year.

Year quarter (1 to 4).

Month of a year.

Month of a year as a number (1 - 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.

Indicate temporal binning by day of the year, so a 10 year sequence would have up to 366 bins.

Day of the week used for discretizing temporal data. This will therefore discretize any temporal sequence into a maximum of 7 bins.

Hour of the day through the week used for discretizing temporal data. This will therefore discretize any temporal sequence into a maximum of 7*24 bins.

Minute through the week used for discretizing temporal data. This will therefore discretize any temporal sequence into a maximum of 7*24*60 bins.

Second through the week used for discretizing temporal data. This will therefore discretize any temporal sequence into a maximum of 7*24*60*60 bins.

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 used for discretizing temporal data. This will ignore year so useful for looking at monthly seasonal patterns through the year.

Day of the year for discretizing temporal data. This will ignore year so useful for looking at seasonal patterns through the year.

Hour of the year used for discretizing temporal data. This will ignore year so useful for looking at seasonal patterns with hourly resolution.

Minute of the year used for discretizing temporal data. This will ignore year so useful for looking at seasonal patterns with one-minute resolution.

Second of the year used for discretizing temporal data. This will ignore year so useful for looking at seasonal patterns with one-second resolution.

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.

Indicate temporal binning by week of year, so a 10 year sequence would have up to 53 bins. Weeks are Sunday-based and days before the first Sunday of the year are considered to be in week 0, the first Sunday of the year is the start of week 1, the second Sunday week 2, etc.

Indicate temporal binning by day of week though the year, so a 10 year sequence would have up to 53*7 bins.

Indicate temporal binning by hour of day though the year, so a 10 year sequence would have up to 52*7*24 bins.

Indicate temporal binning by minute though the year, so a 10 year sequence would have up to 52*7*24*60 bins.

Indicate temporal binning by the second though the year, so a 10 year sequence would have up to 52*7*24*60*60 bins.

Indicate temporal binning into year categories.

Indicate temporal binning with a resolution of quarters so a ten year sequence would have up to 10*4 bins.

Indicate temporal binning with a resolution of months so a ten year sequence would have up to 10*12 bins. Unlike yearMonth, this will also label bins with quarters.

Indicate temporal binning with a resolution of months so a ten year sequence would have up to 10*12 bins.

Indicate temporal binning with a resolution of days so a ten year sequence would have up to approximately 10*12*31 bins.

Indicate temporal binning with a resolution of hours so a ten year sequence would have up to approximately 10*12*31*24 bins.

Indicate temporal binning with a resolution of minutes so a ten year sequence would have up to approximately 10*12*31*24*60 bins.

Indicate temporal binning with a resolution of seconds so a ten year sequence would have up to approximately 10*12*31*24*60*60 bins.

Indicate temporal binning with a resolution of weeks so a ten year sequence would have up to 10*52 bins.

Indicate temporal binning with a resolution of day of week so a ten year sequence would have up to 10*52*7 bins.

Indicate temporal binning with a resolution of hours so a ten year sequence would have up to 10*52*7*24 bins.

Indicate temporal binning with a resolution of minutes so a ten year sequence would have up to 10*52*7*24*60 bins.

Indicate temporal binning with a resolution of seconds so a ten year sequence would have up to 10*52*7*24*60*60 bins.

Indicate temporal binning with a resolution of days so a ten year sequence would have up to approximately 10*365 bins.

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.

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

Specify the maximum number of bins used when discretizing time units. Can be useful as an alternative to explicitly providing a time unit to bin by as it will be inferred from the temporal domain extent and the number of bins. For example, when applied to a dataset of hourly readings for a full year, the following will bin into days:

tuMaxBins 366
tuStep : Float -> TimeUnit -> TimeUnit

Specify the the number of steps between time unit bins, in terms of the least significant unit provided. For example, the following will bin temporal data into biweekly weekly groups:

tuStep 14 yearMonthDate

10. Type Reference

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

type Anchor

Generated by anStart, anMiddle, anEnd and anExpr.

type Aria

Generated by arFlow, arColumn, arRow and arLayer.

Generated by axBoth, axX and axY.

Generated by expr, fiOp, fiOpTrans,bParam, and,or and not.

type Bounds

Generated by boFull and boFlush.

Generated by noClip, clipRect and clipRectExpr.

Generated by grLinear and grRadial.

Generated by caNone, caEach and caAll.

Generated by cocoColumns and cocoSpacing.

Generated by foBoo, foNum, foDate and foUtc.

Generated by facoColumns and facoSpacing.

Generated by columnBy and rowBy.

Generated by numRange and dtRange.

Generated by grX1, grY1, grX2, grY2, grR1, grR2 and grStops.

type HAlign

Generated by haLeft, haCenter, haRight and haExpr.

Generated by imValue, imMean, imMedian, imMax and imMin.

Generated by kName and kQuant, kNominal, kOrdinal, kTemporal and kGeo.

type Legend

Generated by leGradient and leSymbol.

Generated by lmMarker and lmNone.

Generated by lsGroupBy, lsBandwidth and lsAs.

Generated by osNone, osGreedy, osParity and [osExpr].

type Padding

Generated by paSize, paEdges and paEdgesExpr.

Generated by piGroupBy, piLimit and piOp.

Generated by pmNone, pmTransparent and pmMarker.

Generated by prParam, prParamEmpty and prTest.

Generated by qtGroupBy, qtProbs, qtStep and qtAs.

Generated by reShared and reIndependent.

type Resolve

Generated by reAxis, reLegend and reScale.

Generated by sePoint and seInterval.

type Side

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

Generated by stZero, stCenter, stNormalize and stNone.

Generated by stOffset and stSort.

Generated by caButt, caRound, caSquare and caExpr.

Generated by joMiter, joRound, joBevel and joExpr.

Generated by tfBounds, tfGroup and tfExpr.

Generated by ttEncoding, ttData and ttNone.

type Window

Generated by wiAggregateOp, wiOp, wiParam and wiField.