gicentre/elm-vega/2.0.0

NOTE: this package is not compatible with Elm 0.19.1

VegaLite

This module allows you to create Vega-Lite specifications in Elm. A specification is stored as a JSON object which can be sent to a Vega-Lite compiler to generate the graphics. While this a 'pure' Elm library, to create the graphical output you probably want to send a Vega-Lite specification generated by toVegaLite via a port to some JavaScript that invokes the Vega-Lite runtime.

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 a data, mark and encoding specification.

While simple properties like mark may be provided directly, it is usually clearer to label more complex ones such as encodings as separate expressions. This becomes increasingly helpful for visualizations that involve composition of layers, repeats and facets.

Specifications can be built up by chaining a series of functions (such as dataColumn or position in the example below). Functional composition using the << operator allows this to be done compactly.

let
    data =
        dataFromColumns []
            << dataColumn "a" (Strings [ "C", "C", "D", "D", "E", "E" ])
            << dataColumn "b" (Numbers [ 2, 7, 1, 2, 6, 8 ])


    enc =
        encoding
            << position X [ PName "a", PmType Nominal ]
            << position Y [ PName "b", PmType Quantitative, PAggregate Mean ]
in
toVegaLite [ data [], mark Bar [], enc [] ]

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

Data Properties relate to the input data to be visualized. Generated by dataFromColumns, dataFromRows, dataFromUrl and dataFromJson.

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 Properties relate to the symbols used to visualize data items. Generated by mark they include types such as Circle, Bar and Line.

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

Composition Properties allow visualization views to be combined to form more complex visualizations. Generated by layer, repeat, facet, hConcat, vConcat, spec and resolve.

Interaction Properties allow interactions such as clicking, dragging and others generated via a GUI or data stream to influence the visualization. Generated by selection.

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

type alias Spec =
Value

Represents part or all of Vega-Lite specification. Specs can be (and usually are) nested. They can range from a single Boolean value up to the entire Vega-Lite specification.

combineSpecs : List LabelledSpec -> Spec

Combines a list of labelled specifications into a single specification that may be passed to JavaScript for rendering. This is useful when you wish to create a single page with multiple visulizualizations.

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

Creating the Data Specification

Functions and types for declaring the input data to the visualization.

dataFromUrl : String -> List Format -> Data

Declare data source from a url. The url can be a local path on a web server or an external http(s) url. Used to create a data ( property, specification ) pair. An optional list of field formatting instructions can be provided as the second parameter or an empty list to use the default formatting. See the Vega-Lite documentation for details.

enc = ...
toVegaLite
    [ dataFromUrl "data/weather.csv" [ Parse [ ( "date", FoDate "%Y-%m-%d %H:%M" ) ] ]
    , mark Line []
    , enc []
    ]
dataFromColumns : List Format -> List DataColumn -> Data

Declare a data source from a provided list of column values. Each column contains values of the same type, but columns each with a different type are permitted. Columns should all contain the same number of items; if not the dataset will be truncated to the length of the shortest column. An optional list of field formatting instructions can be provided as the first parameter or an empty list to use the default formatting. See the Vega-Lite documentation for details. The columns themselves are most easily generated with dataColumn

data =
    dataFromColumns [ Parse [ ( "Year", FDate "%Y" ) ] ]
        << dataColumn "Animal" (Strings [ "Fish", "Dog", "Cat" ])
        << dataColumn "Age" (Numbers [ 28, 12, 6 ])
        << dataColumn "Year" (Strings [ "2010", "2014", "2015" ])
dataFromRows : List Format -> List DataRow -> Data

Declare a data source from a provided list of row values. Each row contains a list of tuples where the first value is a string representing the column name, and the second the column value for that row. Each column can have a value of a different type but you must ensure that when subsequent rows are added, they match the types of previous values with shared column names. An optional list of field formatting instructions can be provided as the first parameter or an empty list to use the default formatting. See the Vega-Lite documentation for details. The rows themselves are most easily generated with dataRow. Note though that generally if you are creating data inline (as opposed to reading from a file), adding data by column is more efficient and less error-prone.

data =
    dataFromRows [ Parse [ ( "Year", FDate "%Y" ) ] ]
        << dataRow [ ( "Animal", Str "Fish" ), ( "Age", Number 28 ), ( "Year", Str "2010" ) ]
        << dataRow [ ( "Animal", Str "Dog" ), ( "Age", Number 12 ), ( "Year", Str "2014" ) ]
        << dataRow [ ( "Animal", Str "Cat" ), ( "Age", Number 6 ), ( "Year", Str "2015" ) ]
dataFromJson : Spec -> List Format -> Data

Declare a data source from a provided json specification. The most likely use-case for specifying json inline is when creating geojson objects, when geometry, geometryCollection and geoFeatureCollection functions may be used. For more general cases of json creation, consider Json.Encode.

let
    geojson =
        geometry (GeoPolygon [ [ ( -3, 59 ), ( 4, 59 ), ( 4, 52 ), ( -3, 59 ) ] ]) []
in
toVegaLite
    [ width 200
    , height 200
    , dataFromJson geojson []
    , projection [ PType Orthographic ]
    , mark Geoshape []
    ]
dataColumn : String -> DataValues -> List DataColumn -> List DataColumn

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

dataColumn "Animal" (Strings [ "Cat", "Dog", "Mouse"]) []
dataRow : List ( String, DataValue ) -> List DataRow -> List DataRow

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

dataRow [("Animal", Str "Fish"),("Age",Number 28),("Year", Str "2010")] []
geometry : Geometry -> List ( String, DataValue ) -> Spec

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

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

Specifies a list of geo features to be used in a geoShape specification. Each feature object in this collection can be created with the geometry function.

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

Specifies a list of geometry objects to be used in a geoShape specification. Each geometry object in this collection can be created with the geometry function.

geojson =
    geometryCollection
        [ geometry (GeoPolygon [ [ ( -3, 59 ), ( 4, 59 ), ( 4, 52 ), ( -3, 59 ) ] ]) []
        , geometry (GeoPoint -3.5 55.5) []
        ]
type alias Data =
( VLProperty, Spec )

Convenience type annotation label for use with data generation functions.

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

Represents a single column of data. Used when generating inline data with dataColumn.

type alias DataRow =
Spec

Represents a single row of data. Used when generating inline data with dataRow.

type Format
= JSON String
| CSV
| TSV
| TopojsonFeature String
| TopojsonMesh String
| Parse (List ( String, DataType ))

Specifies the type of format a data source uses. If the format is indicated by the file name extension (.tsv, .csv, .json) there is no need to indicate the format explicitly. However this can be useful if (a) the filename extension does not indicate type (e.g. .txt) or you wish to customise the parsing of a file. For example, when specifying the JSON format, its parameter indicates the name of property field containing the attribute data to extract. For details see the Vega-Lite documentation.

= GeoPoint Float Float
| GeoPoints (List ( Float, Float ))
| GeoLine (List ( Float, Float ))
| GeoLines (List (List ( Float, Float )))
| GeoPolygon (List (List ( Float, Float )))
| GeoPolygons (List (List (List ( Float, Float ))))

Specifies the type and content of geometry specifications for programatically creating GeoShapes. These can be mapped to the GeoJson geometry object types where the pluralised type names refer to their Multi prefixed equivalent in the GeoJSON specification.

= FoNumber
| FoBoolean
| FoDate String
| FoUtc String

Indicates the type of data to be parsed when reading input data. For FoDate and FoUtc, the formatting specification can be specified using D3's formatting specifiers or left as an empty string if default date formatting is to be applied. Care should be taken when assuming default parsing of dates because different browsers can parse dates differently. Being explicit about the date format is usually safer.

Creating the Transform Specification

Functions and types for declaring the transformation rules that are applied to data fields or geospatial coordinates before they are encoded visually.

transform : List LabelledSpec -> ( VLProperty, Spec )

Create a single transform from a list of transformation specifications. Note that the order of transformations can be important, especially if labels created with calculateAs, timeUnitAs and binAs 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 (FExpr "datum.year == 2010")
        << calculateAs "datum.sex == 2 ? 'Female' : 'Male'" "gender"
projection : List ProjectionProperty -> ( VLProperty, Spec )

Sets the cartographic projection used for geospatial coordinates. A projection defines the mapping from (longitude,latitude) to an (x,y) plane used for rendering. This is useful when using the Geoshape mark. For further details see the Vega-Lite documentation.

proj =
    projection [ PType Orthographic, PRotate -40 0 0 ]
= PType Projection
| PClipAngle (Maybe Float)
| PClipExtent ClipRect
| PCenter Float Float
| PRotate Float Float Float
| PPrecision Float
| PCoefficient Float
| PDistance Float
| PFraction Float
| PLobes Int
| PParallel Float
| PRadius Float
| PRatio Float
| PSpacing Float
| PTilt Float

Properties for customising a geospatial projection that converts longitude/latitude pairs into planar (x,y) coordinate pairs for rendering and query. For details see the Vega-Lite documentation.

= Albers
| AlbersUsa
| AzimuthalEqualArea
| AzimuthalEquidistant
| ConicConformal
| ConicEqualArea
| ConicEquidistant
| Custom String
| Equirectangular
| Gnomonic
| Mercator
| Orthographic
| Stereographic
| TransverseMercator

Types of geographic map projection. These are based on a subset of those provided by the d3-geo library. For details of available projections see the Vega-Lite documentation. Additional custom projections from d3 can be defined via the Vega API and called from within Elm-Vega setting the projection to Custom proj where proj is the name of the D3 projection to use (e.g. winkel3).

= NoClip
| LTRB Float Float Float Float

Specifies a clipping rectangle in pixel units. In LTRB the order of the four numbers that follow are 'left', 'top', 'right' then 'bottom'. Used when defining the clip extent of a map projection.

Aggregation

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

Defines a set of named aggregation transformations to be used when encoding channels. This is useful when, for example, you wish to apply the same transformation to a number of channels but do not want to define it each time. The first parameter is a list of the named aggregation operations to apply. The second parameter is a list of 'group by' fields. The third parameter is the list of transformations to which this is to be added. For further details see the Vega-Lite documentation.

trans =
    transform
        << aggregate
            [ opAs Min "people" "lowerBound", opAs Max "people" "upperBound" ]
            [ "age" ]
= ArgMax
| ArgMin
| Average
| CI0
| CI1
| Count
| Distinct
| Max
| Mean
| Median
| Min
| Missing
| Q1
| Q3
| Stderr
| Stdev
| StdevP
| Sum
| Valid
| Variance
| VarianceP

Type of aggregation operation. See the Vega-Lite documentation for more details.

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

Create a named aggregation operation on a field that can be added to a transformation. The first parameter is the aggregation 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. For further details see the Vega-Lite documentation.

trans =
    transform
        << aggregate
            [ opAs Min "people" "lowerBound"
            , opAs Max "people" "upperBound"
            ]
            [ "age" ]
timeUnitAs : TimeUnit -> String -> String -> List LabelledSpec -> List LabelledSpec

Creates 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. The final often implicit parameter is a list of previous transformations to which this is added. Note though that usually it is easer to apply the temporal binning directly as part of the encoding as this will automatically format the temporal axis. See the Vega-Lite documentation for further details.

The following example takes a temporal dataset and encodes daily totals from it grouping by month.

trans =
    transform << timeUnitAs Month "date" "monthly"


enc =
    encoding
        << position X [ PName "date", PmType Temporal, PTimeUnit Day ]
        << position Y [ PAggregate Sum, PmType Quantitative ]
        << detail [ DName "monthly", DmType Temporal ]

Binning

bin : List BinProperty -> LabelledSpec

Create a binning transformation to be applied directly to a channel. The type of binning can be customised with a list of BinProperty or an empty list to use the default binning. See the Vega-Lite documentation for more details.

position X [ PName "IMDB_Rating", PmType Quantitative , bin [] ]
List BinProperty
-> String
-> String
-> List LabelledSpec
-> List LabelledSpec

Create a named binning transformation that may be referenced in other Transformations or encodings. This works in a similar way to bin but requires the name of the field to bin and an additional label so it may be referenced in other expressions. The type of binning can be customised with a list of BinProperty or an empty list to use the default binning. See the Vega-Lite documentation for more details. Note that usually, direct binning within an encoding is preferred over this form of bin transformation.

trans =
    transform
        << binAs [ MaxBins 3 ] "IMDB_Rating" "ratingGroup"
= Base Float
| Divide Float Float
| Extent Float Float
| MaxBins Int
| MinStep Float
| Nice Bool
| Step Float
| Steps (List Float)

Type of binning property to customise. See the Vega-Lite documentation for more details.

Data Calculation

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

Creates a new data field based on calculations from existing fields. The first parameter is an expression representing the calculation and the second is the name to give the newly calculated field. This third parameter is a list of any previous calculations to which this is to be added. See the Vega-Lite documentation for further details.

trans =
    transform << calculateAs "datum.sex == 2 ? 'F' : 'M'" "gender"

Filtering

filter : Filter -> List LabelledSpec -> List LabelledSpec

Adds the given filter operation a list of transformations that may be applied to a channel or field. The first parameter is the filter operation and the second, often implicit, parameter is the list of other filter operations to which this should be added in sequence.

trans =
    transform
        << filter (FEqual "Animal" (Str "Cat"))

Filter operations can combine selections and data predicates with BooleanOp expressions:

trans =
    transform
        << filter (FCompose (And (Expr "datum.Weight_in_lbs > 3000") (Selection "brush")))
type Filter
= FEqual String DataValue
| FExpr String
| FCompose BooleanOp
| FSelection String
| FOneOf String DataValues
| FRange String FilterRange

Type of filtering operation. See the Vega-Lite documentation for details.

= NumberRange Float Float
| DateRange (List DateTime) (List DateTime)

A pair of filter range data values. The first argument is the inclusive minimum vale to accept and the second the inclusive maximum.

Relational Joining (lookup)

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

Perform a lookup of named fields between two data sources. This allows you to find values in one data source based on the values in another (like a relational join). 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. As with other transformation functions, the final implicit parameter is a list of any other transformations to which this is to be added.

Unlike lookupAs, this function will only return the specific fields named in the fourth parameter. If you wish to return the entire set of fields in the secondary data source as a single object, use lookupAs.

See the Vega-Lite documentation for further details.

The following would return the values in the age and height fields from lookup_people.csv for all rows where the value in the name column in that file matches the value of person in the primary data source.

data =
    dataFromUrl "data/lookup_groups.csv" []


trans =
    transform
        << lookup "person" (dataFromUrl "data/lookup_people.csv" []) "name" [ "age", "height" ]
String
-> ( VLProperty, Spec )
-> String
-> String
-> List LabelledSpec
-> List LabelledSpec

Perform an object lookup between two data sources. This allows you to find values in one data source based on the values in another (like a relational join). 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 name to be given to the object storing matched values. As with other transformation functions, the final implicit parameter is a list of any other transformations to which this is to be added.

Unlike lookup, this function returns the entire set of field values from the secondary data source when keys match. Those fields are stored as an object with the name provided in the fourth parameter.

See the Vega-Lite documentation for further details.

In the following example, personDetails would reference all the field values in lookup_people.csv for each row where the value in the name column in that file matches the value of person in the primary data source.

data =
    dataFromUrl "data/lookup_groups.csv" []


trans =
    transform
        << lookupAs "person" (dataFromUrl "data/lookup_people.csv" []) "name" personDetails

Creating the Mark Specification

Types and functions for declaring the type of visual marks used in the visualization.

mark : Mark -> List MarkProperty -> ( VLProperty, Spec )

Create a mark specification. All marks must have a type (first parameter) and can optionally be customised with a list of mark properties such as interpolation style for lines. To keep the default style for the mark, just provide an empty list for the second parameter.

mark Circle []
mark Line [ MInterpolate StepAfter ]
type Mark
= Area
| Bar
| Circle
| Geoshape
| Line
| Point
| Rect
| Rule
| Square
| Text
| Tick

Type of visual mark used to represent data in the visualization.

= MAlign HAlign
| MAngle Float
| MBandSize Float
| MBaseline VAlign
| MBinSpacing Float
| MClip Bool
| MColor String
| MCursor Cursor
| MContinuousBandSize Float
| MDiscreteBandSize Float
| MdX Float
| MdY Float
| MFill String
| MFilled Bool
| MFillOpacity Float
| MFont String
| MFontSize Float
| MFontStyle String
| MFontWeight FontWeight
| MInterpolate MarkInterpolation
| MOpacity Float
| MOrient MarkOrientation
| MRadius Float
| MShape Symbol
| MShortTimeLabels Bool
| MSize Float
| MStroke String
| MStrokeDash (List Float)
| MStrokeDashOffset Float
| MStrokeOpacity Float
| MStrokeWidth Float
| MStyle (List String)
| MTension Float
| MText String
| MTheta Float
| MThickness Float

Properties for customising the appearance of a mark. For details see the Vega-Lite documentation.

= Horizontal
| Vertical

Indicates desired orientation of a mark (e.g. horizontally or vertically oriented bars.)

= Basis
| BasisClosed
| BasisOpen
| Bundle
| Cardinal
| CardinalClosed
| CardinalOpen
| Linear
| LinearClosed
| Monotone
| StepAfter
| StepBefore
| Stepwise

Indicates mark interpolation style. See the Vega-Lite documentation for details.

type Symbol
= SymCircle
| SymSquare
| Cross
| Diamond
| TriangleUp
| TriangleDown
| Path String

Identifies the type of symbol. The Path symbol is used to define custom shapes as an SVG path description.

type Cursor
= CAuto
| CDefault
| CNone
| CContextMenu
| CHelp
| CPointer
| CProgress
| CWait
| CCell
| CCrosshair
| CText
| CVerticalText
| CAlias
| CCopy
| CMove
| CNoDrop
| CNotAllowed
| CAllScroll
| CColResize
| CRowResize
| CNResize
| CEResize
| CSResize
| CWResize
| CNEResize
| CNWResize
| CSEResize
| CSWResize
| CEWResize
| CNSResize
| CNESWResize
| CNWSEResize
| CZoomIn
| CZoomOut
| CGrab
| CGrabbing

Represents the type of cursor to display. For an explanation of each type, see the CSS documentation

Creating the Encoding Specification

Types and functions for declaring which data fields are mapped to which channels. Channels can include position on screen (e.g. X,Y), visual mark properties (e.g. color, size, shape), text, hyperlinks, ordering, level of detail and facets (for nested visualization). All can be further customised via a series of properties for determining how that encoding is implemented (e.g. scaling, sorting, spacing).

encoding : List LabelledSpec -> ( VLProperty, Spec )

Create an encoding specification from a list of channel encodings.

enc =
    encoding
        << position X [ PName "Animal", PmType Ordinal ]
        << position Y [ PName "Age", PmType Quantitative ]
        << shape [ MName "Species", MmType Nominal ]
        << size [ MName "Population", MmType Quantitative ]
= Nominal
| Ordinal
| Quantitative
| Temporal
| GeoFeature

Type of measurement to be associated with some channel. Nominal data are categories identified by name alone and which have no intrinsic order. Ordinal data are also categories, but ones which have some natural order. Quantitative data are numeric measurements typically on a continuous scale. Temporal data describe time.

Geospatial types should be set to Quantitative when defining a measurement type for positional encoding and GeoFeature for geographically referenced features. Note that Vega-Lite 2.1 beta instead has latitude and longitude types for encoding with position and a geojson for spatial features, which should not be used in elm-vaga.

Position channel

Relates to where something appears in the visualization.

Position
-> List PositionChannel
-> List LabelledSpec
-> List LabelledSpec

Encode a position channel. The first parameter identifies the channel, the second a list of qualifying options. Usually these will include at least the name of the data field associated with it and its measurement type (either the field name directly, or a reference to a row / column repeat field). The final parameter is a list of any previous channels to which this position channel should be added. This is often implicit when chaining a series of encodings using functional composition.

  enc =
      encoding
        << position X [ PName "Animal", PmTyoe Ordinal ]
= PName String
| PRepeat Arrangement
| PmType Measurement
| PBin (List BinProperty)
| PTimeUnit TimeUnit
| PAggregate Operation
| PScale (List ScaleProperty)
| PAxis (List AxisProperty)
| PSort (List SortProperty)
| PStack StackProperty

Position channel properties used for creating a position channel encoding.

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

Type of position channel, X and Y represent horizontal and vertical axis dimensions on a plane and X2 and Y2 represent secondary axis dimensions where two scales are overlaid in the same space. Geographic positions represented by longitude and latiutude values are identified with Longitude, Latitude and their respective secondary equivalents. Such geographic position channels are subject to a map projection before being placed graphically.

= Ascending
| Descending
| Op Operation
| ByField String
| ByRepeat Arrangement

Allow type of sorting to be customised. For details see the Vega-Lite documentation.

= StZero
| StNormalize
| StCenter
| NoStack

Describes the type of stacking to apply to a bar chart.

= AxDomain Bool
| AxFormat String
| AxGrid Bool
| AxLabelAngle Float
| AxLabelOverlap OverlapStrategy
| AxLabelPadding Float
| AxLabels Bool
| AxMaxExtent Float
| AxMinExtent Float
| AxOffset Float
| AxOrient Side
| AxPosition Float
| AxTicks Bool
| AxTickCount Int
| AxTickSize Float
| AxTitle String
| AxTitleAlign HAlign
| AxTitleAngle Float
| AxTitleMaxLength Float
| AxTitlePadding Float
| AxValues (List Float)
| AxDates (List (List DateTime))
| AxZIndex Int

Axis customisation properties. These are used for customising individual axes. To configure all axes, use AxisConfig with a configuration instead. See the Vega-Lite documentation for more details.

= ONone
| OParity
| OGreedy

Type of overlap strategy to be applied when there is not space to show all items on an axis. See the Vega-Lite documentation for more details.

type Side
= STop
| SBottom
| SLeft
| SRight

Represents one side of a rectangular space.

type HAlign
= AlignCenter
| AlignLeft
| AlignRight

Indicates the horizontal alignment of some text such as on an axis or legend.

type VAlign
= AlignTop
| AlignMiddle
| AlignBottom

Indicates the vertical alignment of some text that may be attached to a mark.

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

Indicates the weight options for a font.

= Year
| YearQuarter
| YearQuarterMonth
| YearMonth
| YearMonthDate
| YearMonthDateHours
| YearMonthDateHoursMinutes
| YearMonthDateHoursMinutesSeconds
| Quarter
| QuarterMonth
| Month
| MonthDate
| Date
| Day
| Hours
| HoursMinutes
| HoursMinutesSeconds
| Minutes
| MinutesSeconds
| Seconds
| SecondsMilliseconds
| Milliseconds

Describes a unit of time. Useful for encoding and transformations. See the Vega-Lite documentation for further details.

Mark channels

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

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

Encode a size channel. The first parameter is a list of mark channel properties that characterise the way a data field is encoded by size. The second parameter is a list of any previous channels to which this size channel should be added.

size [ MName "Age", MmType Quantitative ] []
color : List MarkChannel -> List LabelledSpec -> List LabelledSpec

Encode a color channel. The first parameter is a list of mark channel properties that characterise the way a data field is encoded by color. The second parameter is a list of any previous channels to which this color channel should be added.

color [ MName "Species", MmType Nominal ] []
opacity : List MarkChannel -> List LabelledSpec -> List LabelledSpec

Encode an opacity channel. The first parameter is a list of mark channel properties that characterise the way a data field is encoded by opacity. The second parameter is a list of any previous channels to which this opacity channel should be added.

opacity [ MName "Age", MmType Quantitative ] []
shape : List MarkChannel -> List LabelledSpec -> List LabelledSpec

Encode a shape channel. The first parameter is a list of mark channel properties that characterise the way a data field is encoded by shape. The second parameter is a list of any previous channels to which this shape channel should be added.

shape [ MName "Species", MmType Nominal ] []
= MName String
| MRepeat Arrangement
| MmType Measurement
| MScale (List ScaleProperty)
| MBin (List BinProperty)
| MTimeUnit TimeUnit
| MAggregate Operation
| MLegend (List LegendProperty)
| MSelectionCondition
BooleanOp
(List MarkChannel)
(List MarkChannel)
| MDataCondition BooleanOp (List MarkChannel) (List MarkChannel)
| MPath String
| MNumber Float
| MString String
| MBoolean Bool

Mark channel properties used for creating a mark channel encoding.

= LEntryPadding Float
| LFormat String
| LOffset Float
| LOrient LegendOrientation
| LPadding Float
| LTickCount Float
| LTitle String
| LType Legend
| LValues LegendValues
| LZIndex Int

Legend properties. For more detail see the Vega-Lite documentation.

type Legend
= Gradient
| Symbol

Indicates the type of legend to create. Gradient legends are usually used for continuous quantitative data while symbol legends used for categorical data.

= BottomLeft
| BottomRight
| Left
| None
| Right
| TopLeft
| TopRight

Indicates the legend orientation. See the Vega-Lite documentation for more details.

= LDateTimes (List (List DateTime))
| LNumbers (List Float)
| LStrings (List String)

A list of data values suitable for setting legend values.

Text Channels

Relate to the appearance of the text and tooltip elements of the visualization.

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

Encode a text channel. The first parameter is a list of text channel properties that define the channel. The second parameter is a list of any previous channels to which this channel is to be added. This is usually implicit when chaining a set of encodings together with functional composition. See the Vega-Lite documentation for further details on the text and tooltip channels and Vega-Lite formatting documentation for formatting the appearance of the text.

enc =
    encoding
        << position X [ PName "miles", PmType Quantitative ]
        << position Y [ PName "gas", PmType Quantitative ]
        << text [ TName "miles", TmType Quantitative ]
tooltip : List TextChannel -> List LabelledSpec -> List LabelledSpec

Encode a tooltip channel. The first parameter is a list of text channel properties that define the channel. The second parameter is a list of any previous channels to which this channel is to be added. This is usually implicit when chaining a set of encodings together with functional composition. See the Vega-Lite documentation for further details on the text and tooltip channels and Vega-Lite formatting documentation for formatting the appearance of the text.

  enc =
      encoding
          << position X [ PName "Horsepower", PmType Quantitative ]
          << position Y [ PName "Miles_per_Gallon", PmType Quantitative ]
          << tooltip [ TName "Year", TmType Temporal, TFormat "%Y" ]
= TName String
| TRepeat Arrangement
| TmType Measurement
| TBin (List BinProperty)
| TAggregate Operation
| TTimeUnit TimeUnit
| TSelectionCondition
BooleanOp
(List TextChannel)
(List TextChannel)
| TDataCondition BooleanOp (List TextChannel) (List TextChannel)
| TFormat String

Types of text channel property used for displaying text as part of the visualization.

Relates to a clickable URL destination of a mark. Note that 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.

= HName String
| HRepeat Arrangement
| HmType Measurement
| HBin (List BinProperty)
| HAggregate Operation
| HTimeUnit TimeUnit
| HSelectionCondition
BooleanOp
(List HyperlinkChannel)
(List HyperlinkChannel)
| HDataCondition
BooleanOp
(List HyperlinkChannel)
(List HyperlinkChannel)
| HString String

Types of hyperlink channel property used for linking marks or text to URLs.

Order channels

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

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

Encode an order channel. The first parameter is a list of order field definitions to define the channel. The second parameter is a list of any previous channels to which this order channel is to be added.

enc =
    encoding
        << position X [ PName "miles", PmType Quantitative ]
        << position Y [ PName "gas", PmType Quantitative ]
        << order [ OName "year", OmType Temporal ]
= OName String
| ORepeat Arrangement
| OmType Measurement
| OBin (List BinProperty)
| OAggregate Operation
| OTimeUnit TimeUnit
| OSort (List SortProperty)

Properties of an ordering channel used for sorting data fields.

Facet channels

Channels for faceting single plots into small multiples. Can be used to create trellis plots or other arrangements in rows and columns. See the Vega-Lite documentation for further details. 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. This should include at least the name of data the field and its measurement type. The final parameter is a list of any previous channels to which this is to be added. This is usually implicit when chaining encodings using functional composition

enc =
    encoding
        << position X [ PName "people", PmType Quantitative ]
        << position Y [ PName "gender", PmType Nominal ]
        << row [ FName "age", FmType Ordinal ]
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. The final parameter is a list of any previous channels to which this is to be added. This is usually implicit when chaining encodings using functional composition

enc =
    encoding
        << position X [ PName "people", PmType Quantitative ]
        << position Y [ PName "gender", PmType Nominal ]
        << column [ FName "age", FmType Ordinal ]

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. This allows, for example a line chart with multiple lines to be created – one for each group. See the Vega-Lite documentation for more information.

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. The second parameter is a list of any previous channels to which this detail channel should be added. See the Vega-Lite documentation for details.

detail [ DName "Species", DmType Nominal ] []
= DName String
| DmType Measurement
| DBin (List BinProperty)
| DTimeUnit TimeUnit
| DAggregate Operation

Level of detail channel properties used for creating a grouped channel encoding.

Scaling

Used to specify how the encoding of a data field should be applied.

= SType Scale
| SDomain ScaleDomain
| SRange ScaleRange
| SScheme String (List Float)
| SPadding Float
| SPaddingInner Float
| SPaddingOuter Float
| SRangeStep (Maybe Float)
| SRound Bool
| SClamp Bool
| SInterpolate CInterpolate
| SNice ScaleNice
| SZero Bool
| SReverse Bool

Individual scale property. These are used to customise an individual scale transformation. To customise all scales use config and supply relevant ScaleConfig values. For more details see the Vega-Lite documentation

type Scale
= ScLinear
| ScPow
| ScSqrt
| ScLog
| ScTime
| ScUtc
| ScSequential
| ScOrdinal
| ScBand
| ScPoint
| ScBinLinear
| ScBinOrdinal

Used to indicate the type of scale transformation to apply.

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

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

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

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

color
    [ MName "year"
    , MmType Ordinal
    , MScale <| domainRangeMap ( 1955, "#e6959c" ) ( 2000, "#911a24" )
    ]
= DNumbers (List Float)
| DStrings (List String)
| DDateTimes (List (List DateTime))
| DSelection String
| Unaggregated

Describes the scale domain (type of data in scale). For full details see the Vega-Lite documentation.

= RNumbers (List Float)
| RStrings (List String)
| RName String

Describes a scale range of scale output values. For full details see the Vega-Lite documentation.

= NMillisecond
| NSecond
| NMinute
| NHour
| NDay
| NWeek
| NMonth
| NYear
| NInterval TimeUnit Int
| IsNice Bool
| NTickCount Int

Describes the way a scale can be rounded to 'nice' numbers. For full details see the Vega-Lite documentation.

= CubeHelix Float
| CubeHelixLong Float
| Hcl
| HclLong
| Hsl
| HslLong
| Lab
| Rgb Float

Indicates the type of color interpolation to apply, when mapping a data field onto a color scale. Note that color interpolation cannot be applied with the default sequential color scale, so additionally, you should set the SType to another continuous scale such as linear, pow etc.

Of the interpolation options below Rgb, CubeHelix and CubeHelixLong also require a gamma value (with 1 being a recommended default to provide). For details see the Vega-Lite documentation.

Creating view compositions

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

layer : List Spec -> ( VLProperty, Spec )

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

let
    spec1 = ...
    spec2 = ...
in
toVegaLite
    [ dataFromUrl "data/driving.json" []
    , layer [ spec1, spec2 ]
    ]
hConcat : List Spec -> ( VLProperty, Spec )

Assigns a list of specifications to be juxtaposed horizontally in a visualization.

let
    spec1 = ...
    spec2 = ...
in
toVegaLite
    [ dataFromUrl "data/driving.json" []
    , hConcat [ spec1, spec2 ]
    ]
vConcat : List Spec -> ( VLProperty, Spec )

Assigns a list of specifications to be juxtaposed vertically in a visualization.

let
    spec1 = ...
    spec2 = ...
in
toVegaLite
    [ dataFromUrl "data/driving.json" []
    , vConcat [ spec1, spec2 ]
    ]
resolve : List LabelledSpec -> ( VLProperty, Spec )

Determine whether scales, axes or legends in composite views should share channel encodings. This allows, for example, two different color encodings to be created in a layered view, which otherwise by default would share color channels between layers. Each resolution rule should be in a tuple pairing the channel to which it applies and the rule type.

let
    res =
        resolve
            << resolution (RLegend [ ( ChColor, Independent ) ])
in
toVegaLite
    [ dataFromUrl "data/movies.json" []
    , vConcat [ heatSpec, barSpec ]
    , res []
    ]

For more information see the Vega-Lite documentation.

resolution : Resolve -> List LabelledSpec -> List LabelledSpec

Define a single resolution option to be applied when scales, axes or legends in composite views share channel encodings. This allows, for example, two different color encodings to be created in a layered view, which otherwise by default would share color channels between layers. 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, the second a list of previous resolutions to which this one may be added.

resolve
    << resolution (RScale [ ( ChY, Independent ) ])
type Resolve
= RAxis (List ( Channel, Resolution ))
| RLegend (List ( Channel, Resolution ))
| RScale (List ( Channel, Resolution ))

Used to determine how a channel's axis, scale or legend domains should be resolved if defined in more than one view in a composite visualization. See the Vega-Lite documentation for details.

type Channel
= ChX
| ChY
| ChX2
| ChY2
| ChColor
| ChOpacity
| ChShape
| ChSize

Indicates a channel type to be used in a resolution specification.

= Shared
| Independent

Indicated whether or not a scale domain should be independent of others in a composite visualization. See the Vega-Lite documentation for details.

Faceted views

These are 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 (in rows or columns). For details see the Vega-Lite documentation

repeat : List RepeatFields -> ( VLProperty, Spec )

Define the fields that will be used to compose rows and columns of a set of small multiples. This is used where the encoding of the visualization in small multiples 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.

spec = ...
toVegaLite
    [ repeat [ ColumnFields [ "Cat", "Dog", "Fish" ] ]
    , ( Spec, asSpec spec )
    ]

See the Vega-Lite documentation for further details.

= RowFields (List String)
| ColumnFields (List String)

Create a list of fields to use in set of repeated small multiples. The list of fields named here can be referenced in an encoding with PRepeat Column, PRepeat Row etc.

facet : List FacetMapping -> ( VLProperty, Spec )

Defines the fields that will be used to facet a view in rows or columns to create a set of small multiples. This is used where 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.

spec = ...
toVegaLite
    [ facet [ RowBy [ FName "Origin", FmType Nominal ] ]
    , specifcation spec
    ]

See the Vega-Lite documentation for further details.

= ColumnBy (List FacetChannel)
| RowBy (List FacetChannel)

Provides details of the mapping between a row or column and its field definitions in a set of faceted small multiples. For details see the Vega-Lite documentation

= FName String
| FmType Measurement
| FBin (List BinProperty)
| FAggregate Operation
| FTimeUnit TimeUnit
| FHeader (List HeaderProperty)

Types of facet channel property used for creating a composed facet view of small multiples.

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. Whereas for repeated and faceted specs, the entire specification is provided.

enc1 = ...
spec1 =
    asSpec [ enc1, mark Line [] ]
specification : Spec -> ( VLProperty, Spec )

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

spec = ...
toVegaLite
    [ facet [ RowBy [ FName "Origin", FmType Nominal ] ]
    , specifcation spec
    ]
= Column
| Row

Idenfies whether a repeated/faceted view is arranged in rows or columns.

= HFormat String
| HTitle String

Represents a facet header property. For details, see the Vega-Lite documentation

Creating Selections for Interaction

Selections are the way in which interactions (such as clicking or dragging) can be responded to in a visualization. They transform interactions into data queries. For details, see the Vega-Lite documentation.

selection : List LabelledSpec -> ( VLProperty, Spec )

Create a full selection specification from a list of selections. For details see the Vega-Lite documentation.

selection =
    selection << select "view" Interval [ Bind Scales ]
String
-> Selection
-> List SelectionProperty
-> List LabelledSpec
-> List LabelledSpec

Create a single named selection that may be applied to a data query or transformation. The first two parameters specify the name to be given to the selection for later reference and the type of selection made. The third allows additional selection options to be specified. The fourth is a list of selections to which this is added, which is commonly implicit when chaining a series of selections together with functional composition.

sel =
    selection
        << select "view" Interval [ Bind Scales ] []
        << select "myBrush" Interval []
        << select "myPaintbrush" Multi [ On "mouseover", Nearest True ]
= Single
| Multi
| Interval

Indicates the type of selection to be generated by the user. Single allows one mark at a time to be selected. 'Multi' allows multiple items to be selected (e.g. with shift-click). 'Interval' allows a bounding rectangle to be dragged by user to select all items intersecting with it.

= On String
| Translate String
| Zoom String
| Fields (List String)
| Encodings (List Channel)
| Empty
| ResolveSelections SelectionResolution
| SelectionMark (List SelectionMarkProperty)
| BindScales
| Bind (List Binding)
| Nearest Bool
| Toggle String

Properties for customising the nature of the selection. See the Vega-Lite documentation for details. When linking a selection property to an event stream with On, Translate or Zoom, a String should be provided describing the event stream as detailed in the Vega event stream documentation. If an empty string is provided, the property is set to false. The Toggle option expects a Vega expression that evaluates to either true or false.

type Binding
= IRange String (List InputProperty)
| ICheckbox String (List InputProperty)
| IRadio String (List InputProperty)
| ISelect String (List InputProperty)
| IText String (List InputProperty)
| INumber String (List InputProperty)
| IDate String (List InputProperty)
| ITime String (List InputProperty)
| IMonth String (List InputProperty)
| IWeek String (List InputProperty)
| IDateTimeLocal String (List InputProperty)
| ITel String (List InputProperty)
| IColor String (List InputProperty)

Describes the binding property of a selection based on some HTML input element such as a checkbox or radio button. For details see the Vega-Lite documentation and the Vega input binding documentation

= Debounce Float
| Element String
| InOptions (List String)
| InMin Float
| InMax Float
| InName String
| InStep Float
| InPlaceholder String

GUI Input properties. The type of relevant property will depend on the type of input element selected. For example an InRange (slider) can have numeric min, max and step values; InSelect (selector) has a list of selection label options. For details see the Vega input element binding documentation. The debounce property, available for all input types allows a delay in input event handling to be added in order to avoid unnecessary event broadcasting. The Element property is an optional CSS selector indicating the parent element to which the input element should be added. This allows the option of the input element to be outside the visualization container.

= Global
| Union
| Intersection

Determines how selections in faceted or repeated views are resolved. See the Vege-Lite documentation for details

= SMFill String
| SMFillOpacity Float
| SMStroke String
| SMStrokeOpacity Float
| SMStrokeWidth Float
| SMStrokeDash (List Float)
| SMStrokeDashOffset Float

Properties for customising the appearance of an interval selection mark (dragged rectangle). For details see the Vega-Lite documentation.

Making conditional channel encodings

Sometimes it is useful to make channel encoding conditional on something. For example, on the result of some interaction such as clicking or dragging or some data property such whether null or an outlier. MSelectionCondition (and TSelectionCondition) will encode a mark (or text) dependent on an interactive selection. MDataCondition (and TDataCondition) will encode it dependening on some data property.

For interaction, once a selection has been defined and named, supplying a set of MSelectionCondition encodings allow mark encodings to become dependent on that selection. MSelectionCondition is followed firstly by a Boolean expression relating to the selection upon which it is dependent, then an 'if' and an 'else' clause. Each clause is a list of mark field encodings that should be applied when the selection is true (the 'if clause') and when it is false (the 'else clause'). The color encoding below is saying "whenever data marks are selected with an interval mouse drag, encode the cylinder field with an ordinal color scheme, else make them grey".

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


  enc =
      encoding
          << position X [ PName "Horsepower", PmType Quantitative ]
          << position Y [ PName "Miles_per_Gallon", PmType Quantitative ]
          << color
              [ MSelectionCondition (SelectionName "myBrush")
                  [ MName "Cylinders", MmType Ordinal ]
                  [ MString "grey" ]
              ]

In a similar way, MDataCondition will encocode a mark in one of two ways depending on whether a predicate test is satisfied.

  enc =
      encoding
          << position X [ PName "IMDB_Rating", PmType Quantitative ]
          << position Y [ PName "Rotten_Tomatoes_Rating", PmType Quantitative ]
            << color
                [ MDataCondition
                    (Or (Expr "datum.IMDB_Rating === null")
                        (Expr "datum.Rotten_Tomatoes_Rating === null")
                    )
                    [ MString "#ddd" ]
                    [ MString "#0099ee" ]
                ]

For details, see the Vega-Lite documentation.

= Expr String
| Selection String
| SelectionName String
| And BooleanOp BooleanOp
| Or BooleanOp BooleanOp
| Not BooleanOp

Used for creating logical compositions. For example

color
    [ MSelectionCondition (Or (SelectionName "alex") (SelectionName "morgan"))
        [ MAggregate Count, MName "*", MmType Quantitative ]
        [ MString "gray" ]
    ]

Logical compositions can be nested to any level. For example

Not (And (Expr "datum.IMDB_Rating === null") (Expr "datum.Rotten_Tomatoes_Rating === null") )

Global Configuration

Configuration options that affect the entire visualization. These are in addition to the data and transform options described above.

name : String -> ( VLProperty, Spec )

Provides an optional name to be associated with the visualization.

enc = ...
toVegaLite
    [ name "PopGrowth"
    , dataFromUrl "data/population.json" []
    , mark Bar []
    , enc []
    ]
title : String -> ( VLProperty, Spec )

Provide an optional title to be displayed in the visualization.

enc = ...
toVegaLite
    [ title "Population Growth"
    , dataFromUrl "data/population.json" []
    , mark Bar []
    , enc []
    ]
description : String -> ( VLProperty, Spec )

Provides an optional description to be associated with the visualization.

enc = ...
toVegaLite
    [ description "Population change of key regions since 1900"
    , dataFromUrl "data/population.json" []
    , mark Bar []
    , enc []
    ]
height : Float -> ( VLProperty, Spec )

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

enc = ...
toVegaLite
    [ height 300
    , dataFromUrl "data/population.json" []
    , mark Bar []
    , enc []
    ]
width : Float -> ( VLProperty, Spec )

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

enc = ...
toVegaLite
    [ width 500
    , dataFromUrl "data/population.json" []
    , mark Bar []
    , enc []
    ]
padding : Padding -> ( VLProperty, Spec )

Set the padding around the visualization in pixel units. The way padding is interpreted will depend on the autosize properties. See the Vega-Lite documentation for details.

enc = ...
toVegaLite
    [ width 500
    , padding (PEdges 20 10 5 15)
    , dataFromUrl "data/population.json" []
    , mark Bar []
    , enc []
    ]
autosize : List Autosize -> ( VLProperty, Spec )

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

enc = ...
toVegaLite
    [ width 250
    , height 300
    , autosize [ AFit, APadding, AResize ]
    , dataFromUrl "data/population.json" []
    , mark Bar []
    , enc []
    ]
background : String -> ( VLProperty, Spec )

Set the background color of the visualization. Should be specified with a CSS string such as #ffe or rgb(200,20,150). If not specified the background will be transparent.

enc = ...
toVegaLite
    [ background "rgb(251,247,238)"
    , dataFromUrl "data/population.json" []
    , mark Bar []
    , enc []
    ]
configure : List LabelledSpec -> ( VLProperty, Spec )

Create a single global configuration from a list of configuration specifications. Configurations are applied to all relevant items in the specification. See the Vega-Lite documentation for more details.

config =
    configure
        << configuration (Axis [ DomainWidth 1 ])
        << configuration (View [ Stroke (Just "transparent") ])
        << configuration (SelectionStyle [ ( Single, [ On "dblclick" ] ) ])
configuration : ConfigurationProperty -> List LabelledSpec -> List LabelledSpec

Defines a single configuration option to be applied globally across the visualization. The first parameter identifies the type of configuration, the second a list of previous configurations to which this one may be added.

configuration (Axis [ DomainWidth 4 ]) []
= AreaStyle (List MarkProperty)
| Autosize (List Autosize)
| Axis (List AxisConfig)
| AxisX (List AxisConfig)
| AxisY (List AxisConfig)
| AxisLeft (List AxisConfig)
| AxisRight (List AxisConfig)
| AxisTop (List AxisConfig)
| AxisBottom (List AxisConfig)
| AxisBand (List AxisConfig)
| Background String
| BarStyle (List MarkProperty)
| CircleStyle (List MarkProperty)
| CountTitle String
| FieldTitle FieldTitleProperty
| Legend (List LegendConfig)
| LineStyle (List MarkProperty)
| MarkStyle (List MarkProperty)
| NamedStyle String (List MarkProperty)
| NumberFormat String
| Padding Padding
| PointStyle (List MarkProperty)
| Projection (List ProjectionProperty)
| Range (List RangeConfig)
| RectStyle (List MarkProperty)
| RemoveInvalid Bool
| RuleStyle (List MarkProperty)
| Scale (List ScaleConfig)
| SelectionStyle (List ( Selection, List SelectionProperty ))
| SquareStyle (List MarkProperty)
| Stack StackProperty
| TextStyle (List MarkProperty)
| TickStyle (List MarkProperty)
| TitleStyle (List TitleConfig)
| TimeFormat String
| View (List ViewConfig)

Type of configuration property to customise. See the Vega-Lite documentation for details.

= AContent
| AFit
| ANone
| APad
| APadding
| AResize

Indicates the auto-sizing characteristics of the visualization such as amount of padding, whether it should fill the parent container etc. For more details see the Vega-Lite documentation

type Padding
= PSize Float
| PEdges Float Float Float Float

Represents padding dimensions in pixel units. PSize will set the same value on all four edges of a rectangular container while PEdges can be used to specify different sizes on each edge in order left, top, right, bottom.

= BandPosition Float
| Domain Bool
| DomainColor String
| DomainWidth Float
| MaxExtent Float
| MinExtent Float
| Grid Bool
| GridColor String
| GridDash (List Float)
| GridOpacity Float
| GridWidth Float
| Labels Bool
| LabelAngle Float
| LabelColor String
| LabelFont String
| LabelFontSize Float
| LabelLimit Float
| LabelOverlap OverlapStrategy
| LabelPadding Float
| ShortTimeLabels Bool
| Ticks Bool
| TickColor String
| TickRound Bool
| TickSize Float
| TickWidth Float
| TitleAlign HAlign
| TitleAngle Float
| TitleBaseline VAlign
| TitleColor String
| TitleFont String
| TitleFontWeight FontWeight
| TitleFontSize Float
| TitleLimit Float
| TitleMaxLength Float
| TitlePadding Float
| TitleX Float
| TitleY Float

Axis configuration options for customising all axes. See the Vega-Lite documentation for more details.

= CornerRadius Float
| FillColor String
| Orient LegendOrientation
| Offset Float
| StrokeColor String
| LeStrokeDash (List Float)
| LeStrokeWidth Float
| LePadding Float
| GradientLabelBaseline VAlign
| GradientLabelLimit Float
| GradientLabelOffset Float
| GradientStrokeColor String
| GradientStrokeWidth Float
| GradientHeight Float
| GradientWidth Float
| LeLabelAlign HAlign
| LeLabelBaseline VAlign
| LeLabelColor String
| LeLabelFont String
| LeLabelFontSize Float
| LeLabelLimit Float
| LeLabelOffset Float
| LeShortTimeLabels Bool
| EntryPadding Float
| SymbolColor String
| SymbolType Symbol
| SymbolSize Float
| SymbolStrokeWidth Float
| LeTitleAlign HAlign
| LeTitleBaseline VAlign
| LeTitleColor String
| LeTitleFont String
| LeTitleFontSize Float
| LeTitleFontWeight FontWeight
| LeTitleLimit Float
| LeTitlePadding Float

Legend configuration options. For more detail see the Vega-Lite documentation.

= SCBandPaddingInner Float
| SCBandPaddingOuter Float
| SCClamp Bool
| SCMaxBandSize Float
| SCMinBandSize Float
| SCMaxFontSize Float
| SCMinFontSize Float
| SCMaxOpacity Float
| SCMinOpacity Float
| SCMaxSize Float
| SCMinSize Float
| SCMaxStrokeWidth Float
| SCMinStrokeWidth Float
| SCPointPadding Float
| SCRangeStep (Maybe Float)
| SCRound Bool
| SCTextXRangeStep Float
| SCUseUnaggregatedDomain Bool

Scale configuration property. These are used to configure all scales. For more details see the Vega-Lite documentation

= TAnchor APosition
| TAngle Float
| TBaseline VAlign
| TColor String
| TFont String
| TFontSize Float
| TFontWeight FontWeight
| TLimit Float
| TOffset Float
| TOrient Side

Title configuration properties. These are used to configure the default style of all titles within a visualization. For further details see the Vega-Lite documentation

= AStart
| AMiddle
| AEnd

Indicates the anchor position for some text.

= ViewWidth Float
| ViewHeight Float
| Clip Bool
| Fill (Maybe String)
| FillOpacity Float
| Stroke (Maybe String)
| StrokeOpacity Float
| StrokeWidth Float
| StrokeDash (List Float)
| StrokeDashOffset Float

View configuration property. These are used to configure the style of a single view within a visualization such as its size and default fill and stroke colors. For further details see the Vega-Lite documentation

= RCategory String
| RDiverging String
| RHeatmap String
| ROrdinal String
| RRamp String
| RSymbol String

Properties for customising the colors of a range. The parameter should be a named color scheme such as accent or purpleorange-11. For details see the Vega-Lite documentation.

General Data types

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

= Boolean Bool
| DateTime (List DateTime)
| Number Float
| Str String

A single data value. This is used when a function can accept values of different types (e.g. either a number or a string).

= Booleans (List Bool)
| DateTimes (List (List DateTime))
| Numbers (List Float)
| Strings (List String)

A list of data values. This is used when a function can accept lists of different types (e.g. either a list of numbers or a list of strings).

= DTYear Int
| DTQuarter Int
| DTMonth MonthName
| DTDate Int
| DTDay DayName
| DTHours Int
| DTMinutes Int
| DTSeconds Int
| DTMilliseconds Int

Allows a date or time to be represented. This is typically part of a list of DateTime items to provide a specific point in time. For details see the Vega-Lite documentation.

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

Idntifies a month of the year.

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

Identifies the day of the week.