Reputation: 11597
I would like to place category labels in the centre of my bars in a vega lite spec. I want it to look something like this:
Upvotes: 0
Views: 1042
Reputation: 11597
You can use a stack
transform combined with a calculate
transform that computes the midpoint between the start and end to compute label placement.
Here's an example (or view in vega lite editor here)
Note that the aggregate
transform is only needed because, with this dataset, there is one row per year.
{
"data": {"url": "data/barley.json"},
"width": 1000,
"transform": [
{
"aggregate": [{
"op": "sum",
"field": "yield",
"as": "yield"
}],
"groupby": ["site", "variety"]
},
{
"stack": "yield",
"groupby": ["variety"],
"sort": [{"field": "site", "order": "descending"}]
},
{
"calculate": "(datum.yield_start +datum.yield_end)/2",
"as": "sum_yield_mid"
}
],
"layer": [
{
"mark": {"type": "bar"},
"encoding": {
"x": {"type": "nominal", "field": "variety"},
"y": {"type": "quantitative", "field": "yield_start"},
"y2": {"type": "quantitative", "field": "yield_end"},
"color": {"type": "nominal", "field": "site"}
}
},
{
"mark": {"type": "text", "color": "black"},
"encoding": {
"y": {"field": "sum_yield_mid", "type": "quantitative"},
"text": {"field": "site"},
"x": {"type": "nominal", "field": "variety"}
}
}
]
}
Upvotes: 1