如何垂直对齐 Vega-Lite 堆叠条形图数据标签
How to vertically align Vega-Lite stacked bar chart data labels
如何对齐堆叠条形图中的数据标签,使其在每个条形段内垂直居中?在以下示例中,您可以看到文本位于每个条形段的顶部。在条形段较细的地方,数据标签与下面的重叠。我意识到即使标签垂直居中,具有多个相邻的细段也会导致重叠,但我的数据集不太可能出现这种情况。
{
"$schema": "https://vega.github.io/schema/vega-lite/v2.json",
"data": {
"values": [
{"Value": 0.321, "Date": "09/30/2021", "Measure": "Measure 4"},
{"Value": 0.031, "Date": "09/30/2021", "Measure": "Measure 3"},
{"Value": 0.123, "Date": "09/30/2021", "Measure": "Measure 2"},
{"Value": 0.475, "Date": "09/30/2021", "Measure": "Measure 1"}
]
},
"width": 500,
"height": 250,
"resolve": {"scale": {"color": "independent"}},
"layer": [
{
"mark": "bar",
"encoding": {
"y": {
"field": "Value",
"type": "quantitative",
"axis": {"format": ".1%"}
},
"x": {"field": "Date", "type": "nominal", "axis": {"labelAngle": -45}},
"color": {"field": "Measure", "type": "nominal"}
}
},
{
"mark": {"type": "text"},
"encoding": {
"y": {"field": "Value", "type": "quantitative", "stack": "zero"},
"x": {"field": "Date", "type": "nominal"},
"color": {
"field": "Measure",
"type": "nominal",
"scale": {"range": ["white"]},
"legend": null
},
"text": {
"aggregate": "sum",
"field": "Value",
"type": "quantitative",
"format": ".1%"
}
}
}
]
}
您可以使用 stack and calculate 转换来做到这一点。文本层将如下所示:
{
...
"transform": [
{"stack": "Value", "groupby": ["Date"], "as": ["lower", "upper"]},
{"calculate": "(datum.lower + datum.upper) / 2", "as": "midpoint"}
],
"encoding": {
"y": {"field": "midpoint", "type": "quantitative"},
...
}
}
您可以在 vega editor 中查看完整规范:
如何对齐堆叠条形图中的数据标签,使其在每个条形段内垂直居中?在以下示例中,您可以看到文本位于每个条形段的顶部。在条形段较细的地方,数据标签与下面的重叠。我意识到即使标签垂直居中,具有多个相邻的细段也会导致重叠,但我的数据集不太可能出现这种情况。
{
"$schema": "https://vega.github.io/schema/vega-lite/v2.json",
"data": {
"values": [
{"Value": 0.321, "Date": "09/30/2021", "Measure": "Measure 4"},
{"Value": 0.031, "Date": "09/30/2021", "Measure": "Measure 3"},
{"Value": 0.123, "Date": "09/30/2021", "Measure": "Measure 2"},
{"Value": 0.475, "Date": "09/30/2021", "Measure": "Measure 1"}
]
},
"width": 500,
"height": 250,
"resolve": {"scale": {"color": "independent"}},
"layer": [
{
"mark": "bar",
"encoding": {
"y": {
"field": "Value",
"type": "quantitative",
"axis": {"format": ".1%"}
},
"x": {"field": "Date", "type": "nominal", "axis": {"labelAngle": -45}},
"color": {"field": "Measure", "type": "nominal"}
}
},
{
"mark": {"type": "text"},
"encoding": {
"y": {"field": "Value", "type": "quantitative", "stack": "zero"},
"x": {"field": "Date", "type": "nominal"},
"color": {
"field": "Measure",
"type": "nominal",
"scale": {"range": ["white"]},
"legend": null
},
"text": {
"aggregate": "sum",
"field": "Value",
"type": "quantitative",
"format": ".1%"
}
}
}
]
}
您可以使用 stack and calculate 转换来做到这一点。文本层将如下所示:
{
...
"transform": [
{"stack": "Value", "groupby": ["Date"], "as": ["lower", "upper"]},
{"calculate": "(datum.lower + datum.upper) / 2", "as": "midpoint"}
],
"encoding": {
"y": {"field": "midpoint", "type": "quantitative"},
...
}
}
您可以在 vega editor 中查看完整规范: