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.
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.
Created 2021-05-15T17:25:32-07:00 · Edit