Calculate Percentage of Total
View this example in the online editor
Vega-Lite JSON Specification
{
"$schema": "https://vega.github.io/schema/vega-lite/v2.json",
"description": "A bar graph showing what activites consume what percentage of the day.",
"data": {
"values": [
{"Activity": "Sleeping","Time": 8},
{"Activity": "Eating","Time": 2},
{"Activity": "TV","Time": 4},
{"Activity": "Work","Time": 8},
{"Activity": "Exercise","Time": 2}
]
},
"transform": [{
"window": [{
"op": "sum",
"field": "Time",
"as": "TotalTime"
}],
"frame": [null, null]
},
{
"calculate": "datum.Time/datum.TotalTime * 100",
"as": "PercentOfTotal"
}],
"mark": "bar",
"encoding": {
"x": {
"field": "PercentOfTotal",
"type": "quantitative",
"axis": {
"title": "% of total Time"
}
},
"y": {
"field": "Activity",
"type": "nominal",
"scale": {
"rangeStep": 12
}
}
}
}