I am trying to make a stacked bar chart in vega-lite so that I can use it with Deneb in PowerBI. In this simple example), the expected behaviour is that the X-axis should be variety, and the Y-axis should be count of site coloured by site. The text labels should be layered over each coloured section of each bar showing the percentage each site represents from all sites for that variety (so each should be 1/6 or 16.7%). Despite trying many different configurations, I can't get the expected behaviour - there seems to be something wrong with how I am grouping and transforming the data. Any help would be appreciated.
{
"data": {"url": "data/barley.json"},
"width": 400,
"transform": [
{
"joinaggregate": [{"op": "count", "field": "yield", "as": "col_count", "groupby": "variety"}],
"groupby": ["variety"],
"frame": [null, null]
},
{
"joinaggregate": [{"op": "count", "field": "yield", "as": "group_count"}],
"groupby": ["variety", "site"],
"frame": [null, null]
},
{
"calculate": "datum.group_count / datum.col_count",
"as": "variety_percentage",
"groupby": ["variety", "site"]
}
],
"encoding": {
"y": {
"type": "quantitative",
"aggregate": "sum",
"field": "yield",
"stack": "zero"
},
"x": {"type": "nominal", "field": "variety"}
},
"layer": [
{
"mark": "bar",
"encoding": {"color": {"type": "nominal", "field": "site"}}
},
{
"mark": {"type": "text", "color": "black", "dx": 0, "dy": -10},
"encoding": {
"detail": {"type": "nominal", "field": "variety_percentage"},
"text": {
"type": "quantitative",
"aggregate": "none",
"field": "variety_percentage",
"format": ".1%"
}
}
}
]
}
Here you go. Make sure you only include allowed values in your transforms and pay close attention to the documentation. Your logs were full of warnings which will break the spec.
{
"data": {"url": "data/barley.json"},
"width": 400,
"transform": [
{
"joinaggregate": [{"op": "count", "field": "yield", "as": "col_count"}],
"groupby": ["variety"]
},
{
"joinaggregate": [{"op": "count", "field": "yield", "as": "group_count"}],
"groupby": ["variety", "site"]
},
{
"calculate": "datum.group_count / datum.col_count",
"as": "variety_percentage"
}
],
"layer": [
{
"mark": "bar",
"encoding": {
"y": {
"type": "quantitative",
"field": "yield",
"stack": "zero",
"aggregate": "sum"
},
"x": {"type": "nominal", "field": "variety"},
"color": {"type": "nominal", "field": "site"}
}
},
{
"mark": {"type": "text", "color": "black", "dx": 0, "dy": 15},
"encoding": {
"x": {"type": "nominal", "field": "variety"},
"y": {"field": "yield", "stack": "zero", "aggregate": "sum"},
"detail": {"type": "nominal", "field": "site"},
"text": {
"type": "quantitative",
"field": "variety_percentage",
"format": "0.1%"
}
}
}
]
}