175 words
1 minute
Vega-Lite bar charts in the same order as the data
Anubhav Gain
2024-11-11

Vega-Lite bar charts in the same order as the data#

I’ve been puzzling over this one for a couple of years now, and I finally figured out the solution.

The Vega-Lite charting library can generate bar charts using a JSON definition that looks like this:

{
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"description": "A simple bar chart with embedded data.",
"data": {
"values": [
{"bar_label": "startups", "bar_quantity": 157},
{"bar_label": "webdevelopment", "bar_quantity": 166},
{"bar_label": "quora", "bar_quantity": 1003},
{"bar_label": "conferences", "bar_quantity": 152},
{"bar_label": "datasette", "bar_quantity": 111}
]
},
"mark": "bar",
"encoding": {
"x": {
"field": "bar_label",
"title": "Label",
"type": "nominal",
"axis": {"labelAngle": 90}
},
"y": {"field": "bar_quantity", "title": "Quantity", "type": "quantitative"}
}
}

There’s just one catch: Vega-Lite defaults to sorting the bars alphabetically by their nominal label.

Vega_Editor

But sometimes you might want to control that sort order - to have the order that the bars are displayed in directly reflect the order of the data that you passed in.

To do this, pass "sort": null as an option to the x encoding:

Vega_Editor

Open this example in the Vega Editor

Vega-Lite Sorting documentation.

Vega-Lite bar charts in the same order as the data
https://mranv.pages.dev/posts/vega-lite-bar-charts-in-the-same-order-as-the-data/
Author
Anubhav Gain
Published at
2024-11-11
License
CC BY-NC-SA 4.0