Sorting

Edit this page
{
  "data": ... ,
  "mark": ... ,
  "encoding": {
    "x": {
      "field": ...,
      "type": ...,
      "sort": ...,         // sort
      ...
    },
    "y": ...,
    ...
  },
  ...
}

The sort property of a mark properties channel determines the order of the scale domain. Supported sort values depend on the field’s scale type.

Sorting Continuous Scales

If the channel has a continuous scale (quantitative or time), sort can have the following values:

  • "ascending" (Default) – the field is sorted by the field’s value in ascending order.
  • "descending" – the field is sorted by the field’s value in descending order.

Example: Reversed X-Scale

Setting x’s sort to "descending" reverses the x-axis. Thus, the following visualization’s x-axis starts on the maximum value of the field “Horsepower” and ends on zero.

Sorting Discrete Scales

If the channel has a discrete scale (band, point or ordinal), the field’s values of the channel can be sorted in the following ways:

1) Sorting by the values’ natural order in Javascript. For example, "a" < "b". In this case, sort can be:

  • "ascending" (Default) – sort by the field’s value in ascending order.
  • "descending" – sort by the field’s value in descending order.

2) Sorting by aggregated value of another “sort” field. In this case, sort is a sort field definition object, which has the following properties:

Property Type Description
field String | RepeatRef

The data field to sort by.

Default value: If unspecified, defaults to the field specified in the outer data reference.

op AggregateOp

Required. An aggregate operation to perform on the field prior to sorting (e.g., "count", "mean" and "median"). This property is required in cases where the sort field and the data reference field do not match. The input data objects will be aggregated, grouped by the encoded data field.

For a full list of operations, please see the documentation for aggregate.

order String

The sort order. One of "ascending" (default) or "descending".

3) Unsorted – null – The field is not sorted. This is equivalent to specifying sort: false in Vega’s scales.

4) Specify custom order by providing custom scale’s domain. (In this case, you don’t need to use sort property.)

Example: Sorting Ordinal Scale by Another Field

The following example sorts x by mean of Horsepower.