vega-lite - Vega Lite:标准化堆积条形图 + 叠加百分比作为文本
问题描述
我有一个类似于这样的堆叠标准化条形图: https ://vega.github.io/editor/#/examples/vega-lite/stacked_bar_normalize 我试图将相关百分比(每个条形段)显示为文本类似于:https ://gist.github.com/pratapvardhan/00800a4981d43a84efdba0c4cf8ee2e1
我尝试添加一个转换字段来计算百分比,但经过数小时的尝试仍然无法使其工作。我失去了帮助我最好的尝试:
{
"description":
"A bar chart showing the US population distribution of age groups and gender in 2000.",
"data": {
"url": "data/population.json"
},
"transform": [
{"filter": "datum.year == 2000"},
{"calculate": "datum.sex == 2 ? 'Female' : 'Male'", "as": "gender"},
{
"stack": "people",
"offset": "normalize",
"as": ["v1", "v2"],
"groupby": ["age"],
"sort": [{"field": "gender", "order": "descending"}]
}
],
"encoding": {
"y": {
"field": "v1",
"type": "quantitative",
"title": "population"
},
"y2": {"field": "v2"},
"x": {
"field": "age",
"type": "ordinal"
},
"color": {
"field": "gender",
"type": "nominal",
"scale": {
"range": ["#675193", "#ca8861"]
}
}
},
"layer":[
{ "mark": "bar"},
{"mark": {"type": "text", "dx": 0, "dy": 0},
"encoding": {
"color":{"value":"black"},
"text": { "field": "v1", "type": "quantitative", "format": ".1f"}}
}
]
}
解决方案
您可以使用joinaggregate 转换来规范化每个组,然后使用"format": ".1%"
将分数显示为百分比。使用它,无需手动计算堆栈变换;正如您链接到的示例中那样,通过编码指定堆栈更简单。
这是结果(在编辑器中打开):
{
"description": "A bar chart showing the US population distribution of age groups and gender in 2000.",
"data": {"url": "data/population.json"},
"transform": [
{"filter": "datum.year == 2000"},
{"calculate": "datum.sex == 2 ? 'Female' : 'Male'", "as": "gender"},
{
"joinaggregate": [{"op": "sum", "field": "people", "as": "total"}],
"groupby": ["age"]
},
{"calculate": "datum.people / datum.total", "as": "fraction"}
],
"encoding": {
"y": {
"aggregate": "sum",
"field": "people",
"title": "population",
"stack": "normalize"
},
"order": {"field": "gender", "sort": "descending"},
"x": {"field": "age", "type": "ordinal"},
"color": {
"field": "gender",
"type": "nominal",
"scale": {"range": ["#675193", "#ca8861"]}
}
},
"layer": [
{"mark": "bar"},
{
"mark": {"type": "text", "dx": 20, "dy": 0, "angle": 90},
"encoding": {
"color": {"value": "white"},
"text": {"field": "fraction", "type": "quantitative", "format": ".1%"}
}
}
]
}
推荐阅读
- javascript - 为特定功能复制 ng-if
- javascript - 在主函数中调用点击函数
- node.js - 码头工人中的码头工人
- angularjs-ng-click - ng-click 在加载到 div 中的 HTML 中不起作用
- php - 如何从列表元素中的 html 文档调用 php 函数?
- scala - 从 spark udf 记录到驱动程序
- android - 如何在布局边框顶部对齐 FAB
- javascript - 如何将使用指标从 spotfire 发送到谷歌分析
- laravel - 雄辩的缓存结果像 $book->author 吗?
- c# - 将多行脚本从另一个 PowerShell 传递到 PowerShell?