Reputation: 43
I'm having issues with the transform and mark rect in Vega-Lite. I'm using transform to calculate the stack and get the midpoint of the stacks. My goal is to have the rectangles centered within the stacked bars. In the code below, by default, the position of the rectangle is correct when the mark bar is sorted in ascending order. However, when I set it to descending for the bar, the issue arises. I've tried adding "descending" to the mark rect, but it doesn't seem to work. Can someone help me address this issue?
Image:
Upvotes: 1
Views: 113
Reputation: 2451
Your layers were not ordered in the same way. Try this:
{
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"width": 600,
"height": 300,
"datasets": {
"source": [
{"CategoryName": "Mì", "Mi": "24099", "Com": "39755", "Gao": "24599"},
{"CategoryName": "Bún", "Mi": "23842", "Com": "20568", "Gao": "21454"},
{"CategoryName": "Cháo", "Mi": "19265", "Com": "28708", "Gao": "30254"}
]
},
"transform": [
{"fold": ["Mi", "Com", "Gao"], "as": ["type", "result"]},
{
"stack": "result",
"offset": "zero",
"as": ["lower", "upper"],
"groupby": ["CategoryName"]
},
{"calculate": "(datum.upper + datum.lower) / 2", "as": "midpoint"},
{
"stack": "result",
"offset": "zero",
"as": ["lowerReserveOrder", "upperReverseOrder"],
"groupby": ["CategoryName"]
},
{"calculate": "indexof(['Mi', 'Com', 'Gao'], datum.type)", "as": "order"}
],
"layer": [
{
"layer": [
{
"mark": {"type": "bar", "align": "center"},
"encoding": {
"order": {"field": "order", "type": "ordinal"},
"x": {
"field": "CategoryName",
"title": "Category Name",
"type": "ordinal"
},
"y": {
"field": "result",
"type": "quantitative",
"title": "Product Price Sum, Id Sales Mans Sum, Store Id Sum",
"stack": "zero"
},
"color": {
"type": "nominal",
"field": "type",
"title": "",
"scale": {
"range": ["#546BF9", "#FF7557", "#5BB7AF"],
"domain": ["Mi", "Com", "Gao"]
},
"legend": {"orient": "bottom", "direction": "horizontal"}
}
}
},
{
"mark": {
"type": "rect",
"color": "#FFFFFF",
"opacity": 0.6,
"height": 15.6,
"width": 30,
"cornerRadius": 5
},
"encoding": {
"order": {"field": "order", "type": "ordinal"},
"x": {
"field": "CategoryName",
"type": "ordinal",
"title": null,
"axis": {
"labelAngle": 0,
"labelAlign": "center",
"labelPadding": 10
}
},
"y": {"field": "midpoint", "type": "quantitative", "stack": "zero"},
"tooltip": [{"field": "type"}, {"field": "result"}]
}
}
],
"resolve": {"scale": {"color": "independent"}}
}
]
}
Upvotes: 1