Newsletter
TechAnV Blog
Get updates on security engineering, Rust, eBPF, and DevSecOps. No spam, unsubscribe anytime.
Check your inbox and click the confirmation link to complete your subscription.
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:
1{2 "$schema": "https://vega.github.io/schema/vega-lite/v5.json",3 "description": "A simple bar chart with embedded data.",4 "data": {5 "values": [6 {"bar_label": "startups", "bar_quantity": 157},7 {"bar_label": "webdevelopment", "bar_quantity": 166},8 {"bar_label": "quora", "bar_quantity": 1003},9 {"bar_label": "conferences", "bar_quantity": 152},10 {"bar_label": "datasette", "bar_quantity": 111}11 ]12 },13 "mark": "bar",14 "encoding": {15 "x": {16 "field": "bar_label",17 "title": "Label",18 "type": "nominal",19 "axis": {"labelAngle": 90}20 },21 "y": {"field": "bar_quantity", "title": "Quantity", "type": "quantitative"}22 }23}There’s just one catch: Vega-Lite defaults to sorting the bars alphabetically by their nominal label.

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:

Open this example in the Vega Editor
Vega-Lite Sorting documentation.
Newsletter
TechAnV Blog
Get updates on security engineering, Rust, eBPF, and DevSecOps. No spam, unsubscribe anytime.
Check your inbox and click the confirmation link to complete your subscription.