问题描述
我正在尝试创建一个连续金字塔图,但中间的文本似乎无法正确呈现。将标记文本的字段更改为数字不会出现此渲染问题。这是我遵循并修改的示例。 Population Pyramid
{
"$schema": "https://vega.github.io/schema/vega-lite/v5.json","spacing": 0,"hconcat": [
{
"transform": [
{ "filter": { "field": "sentiment","equal": "negative" } }
],"encoding": {
"y": { "field": "type","title": null,"axis": null },"x": {
"field": "sentiment","aggregate": "count","axis": null,"sort": "descending"
}
},"layer": [
{ "mark": "bar","encoding": { "color": { "field": "channel" } } }
]
},{
"width": 100,"view": { "stroke": null },"mark": { "type": "text","align": "center" },"text": { "field": "type" }
}
},{
"mark": "bar","transform": [
{ "filter": { "field": "sentiment","equal": "positive" } }
],"encoding": {
"color": { "field": "channel" },"y": { "field": "type","x": { "field": "sentiment","axis": null }
}
}
],"config": { "view": { "stroke": null },"axis": { "grid": false } },"data": {
"values": [
{
"id": 1,"type": "shops","channel": "line man","sentiment": "negative"
}
]
}
}
解决方法
由于您尚未在文本图表中进行任何聚合,因此每个文本标记都会绘制多次 - 数据中的每个对应行一次。多个文本标记的堆叠使它看起来好像渲染得很差。
为确保每个文本标记只绘制一次,您需要聚合数据。有几种方法可以做到这一点,但这里最简单的是使用相关数字列的 argmin
或 argmax
:
"encoding": {
"y": {"field": "type","axis": null},"text": {"field": "type","aggregate": {"argmin": "id"}}
}