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.
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, dataFromSource 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.
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.
Represents a named Vega-Lite specification, usually generated by an elm-vega
function. You shouldn't need to create LabelledSpec tuples directly, but they
can be useful for type annotations.
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 )
]Functions and types for declaring the input data to the visualization.
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 []
]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" ])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" ) ]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 []
]Declare data from a named source. The source may be from named datasets within
a specification or a named data source created via the
Vega View API.
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
[ datasets [ ( "myData", data [] ), ( "myJson", dataFromJson json [] ) ]
, dataFromSource "myData" []
, mark Bar []
, enc []
]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.
let
data =
dataFromRows []
<< dataRow [ ( "cat", Str "a" ), ( "val", Number 10 ) ]
<< dataRow [ ( "cat", Str "b" ), ( "val", Number 18 ) ]
json =
JE.list
[ JE.object [ ( "cat", JE.string "a" ), ( "val", JE.float 120 ) ]
, JE.object [ ( "cat", JE.string "b" ), ( "val", JE.float 180 ) ]
]
enc = ...
in
toVegaLite
[ datasets [ ( "myData", data [] ), ( "myJson", dataFromJson json [] ) ]
, dataFromSource "myData" []
, mark Bar []
, enc []
]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"]) []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")] []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 ) ] ]) []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" ) ]
]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) []
]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 ])Represents a single column of data. Used when generating inline data with
dataColumn.
Represents a single row of data. Used when generating inline data with
dataRow.
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.
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.
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.
Functions and types for declaring the transformation rules that are applied to data fields or geospatial coordinates before they are encoded visually.
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"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 ]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.
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).
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.
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" ]Type of aggregation operation. See the Vega-Lite documentation for more details.
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" ]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 ]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 [] ]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"Type of binning property to customise. See the Vega-Lite documentation for more details.
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"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 of filtering operation. See the Vega-Lite documentation for details.
A pair of filter range data values. The first argument is the inclusive minimum vale to accept and the second the inclusive maximum.
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" ]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" personDetailsTypes and functions for declaring the type of visual marks used in the visualization.
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 of visual mark used to represent data in the visualization.
Properties for customising the appearance of a mark. For details see the Vega-Lite documentation.
Indicates desired orientation of a mark (e.g. horizontally or vertically oriented bars.)
Indicates mark interpolation style. See the Vega-Lite documentation for details.
Identifies the type of symbol. The Path symbol is used to define custom shapes
as an SVG path description.
Represents the type of cursor to display. For an explanation of each type, see the CSS documentation
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, stroke, shape), text, hyperlinks, ordering, level of detail and facets
(for composed visualizations). All can be further customised via a series of properties
for determining how that encoding is implemented (e.g. scaling, sorting, spacing).
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 ]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 position encoding (Longitude and Latitude) should specify the PmType
as Quantitative. Geographically referenced features encoded as shape marks
should specify MmType as GeoFeature (Vega-Lite currently refers to this type
as geojson).
Relates to where something appears in the visualization.
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 ]Encoding by position will generate an axis by default. To prevent the axis from
appearing, simply provide an empty list of axis properties to PAxis :
enc =
encoding
<< position X [ PName "Animal", PmTyoe Ordinal, PAxis [] ]Position channel properties used for creating a position channel encoding.
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.
Allow type of sorting to be customised. For details see the Vega-Lite documentation.
Describes the type of stacking to apply to a bar chart.
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.
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.
Represents one side of a rectangular space.
Indicates the horizontal alignment of some text such as on an axis or legend.
Indicates the vertical alignment of some text that may be attached to a mark.
Indicates the weight options for a font.
Describes a unit of time. Useful for encoding and transformations. See the Vega-Lite documentation for further details.
Relate to the appearance of the visual marks in the visualization such as their color or size.
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 ] []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 ] []Encoding a color channel will generate a legend by default. To stop the legend
appearing, just supply an empty list of legend properties to MLegend :
color [ MName "Species", MmType Nominal, MLegend [] ] []Encode a fill channel. This acts in a similar way to encoding by color but
only affects the interior of closed shapes. The first parameter is a list of mark
channel properties that characterise the way a data field is encoded by fill.
The second parameter is a list of any previous channels to which this fill channel
should be added.
fill [ MName "Species", MmType Nominal ] []Note that if both fill and color encodings are specified, fill takes precedence.
Encode a stroke channel. This acts in a similar way to encoding by color but
only affects the exterior boundary of marks. The first parameter is a list of mark
channel properties that characterise the way a data field is encoded by stroke.
The second parameter is a list of any previous channels to which this stroke channel
should be added.
stroke [ MName "Species", MmType Nominal ] []Note that if both stroke and color encodings are specified, stroke takes
precedence.
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 ] []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 ] []Mark channel properties used for creating a mark channel encoding. Providing
an empty list to MScale, or MLegend removes the scaling and legend respectively.
Legend properties. For more detail see the Vega-Lite documentation.
Indicates the type of legend to create. Gradient legends are usually used for continuous quantitative data while symbol legends used for categorical data.
Indicates the legend orientation. See the Vega-Lite documentation for more details.
A list of data values suitable for setting legend values.
Relate to the appearance of the text and tooltip elements of the visualization.
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 ]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" ]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.
Encode a hyperlink channel. The first parameter is a list of hyperlink channel properties that characterise the hyperlinking such as the destination url and cursor type. The second parameter is a list of any previous encoding channels to which this hyperlink channel should be added.
hyperlink [ MName "Species", MmType Nominal ] []For further details see the Vega-Lite documentation
Types of hyperlink channel property used for linking marks or text to URLs.
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.
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 ]Properties of an ordering channel used for sorting data fields.
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.
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 ]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 ]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.
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 ] []Level of detail channel properties used for creating a grouped channel encoding.
Used to specify how the encoding of a data field should be applied.
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
Used to indicate the type of scale transformation to apply.
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" )
]
]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" )
]Describes the scale domain (type of data in scale). For full details see the Vega-Lite documentation.
Describes a scale range of scale output values. For full details see the Vega-Lite documentation.
Describes the way a scale can be rounded to 'nice' numbers. For full details see the Vega-Lite documentation.
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.
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
Assigns a list of specifications to superposed layers in a visualization.
let
spec1 = ...
spec2 = ...
in
toVegaLite
[ dataFromUrl "data/driving.json" []
, layer [ spec1, spec2 ]
]Assigns a list of specifications to be juxtaposed horizontally in a visualization.
let
spec1 = ...
spec2 = ...
in
toVegaLite
[ dataFromUrl "data/driving.json" []
, hConcat [ spec1, spec2 ]
]Assigns a list of specifications to be juxtaposed vertically in a visualization.
let
spec1 = ...
spec2 = ...
in
toVegaLite
[ dataFromUrl "data/driving.json" []
, vConcat [ spec1, spec2 ]
]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.
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 ) ])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.
Indicates a channel type to be used in a resolution specification.
Indicated whether or not a scale domain should be independent of others in a composite visualization. See the Vega-Lite documentation for details.
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
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.
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.
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.
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
Types of facet channel property used for creating a composed facet view of small multiples.
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 [] ]Defines a specification object for use with faceted and repeated small multiples.
spec = ...
toVegaLite
[ facet [ RowBy [ FName "Origin", FmType Nominal ] ]
, specifcation spec
]Idenfies whether a repeated/faceted view is arranged in rows or columns.
Represents a facet header property. For details, see the Vega-Lite documentation
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.
Create a full selection specification from a list of selections. For details see the Vega-Lite documentation.
selection =
selection << select "view" Interval [ Bind Scales ]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 ]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.
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.
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
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.
Determines how selections in faceted or repeated views are resolved. See the Vege-Lite documentation for details
Properties for customising the appearance of an interval selection mark (dragged rectangle). For details see the Vega-Lite documentation.
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.
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") )Configuration options that affect the entire visualization. These are in addition to the data and transform options described above.
Provides an optional name to be associated with the visualization.
enc = ...
toVegaLite
[ name "PopGrowth"
, dataFromUrl "data/population.json" []
, mark Bar []
, enc []
]Provide an optional title to be displayed in the visualization.
enc = ...
toVegaLite
[ title "Population Growth"
, dataFromUrl "data/population.json" []
, mark Bar []
, enc []
]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 []
]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 []
]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 []
]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 []
]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 []
]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 []
]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" ] ) ])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 ]) []Type of configuration property to customise. See the Vega-Lite documentation for details.
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
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.
Axis configuration options for customising all axes. See the Vega-Lite documentation for more details.
Legend configuration options. For more detail see the Vega-Lite documentation.
Scale configuration property. These are used to configure all scales. For more details see the Vega-Lite documentation
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
Indicates the anchor position for some text.
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
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.
In addition to more general data types like integers and string, the following types can carry data used in specifications.
A single data value. This is used when a function can accept values of different types (e.g. either a number or a 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).
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.
Idntifies a month of the year.
Identifies the day of the week.
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
markmay 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
dataColumnorpositionin the example below). Functional composition using the<<operator allows this to be done compactly.