根据需求动态设置甘特图高度可以使用Vega-Lite中的Transformations(转化)功能。代码示例如下:
{
"encoding": {
"y": {
"field": "Task",
"type": "ordinal",
"sort": {"field": "StartDate"}
},
"x": {"field": "StartDate", "type": "temporal"},
"x2": {"field": "EndDate", "type": "temporal"}
},
"layer": [
{
"mark": {"type": "bar", "height": {"step": 20}},
"encoding": {
"color": {"field": "Status", "type": "nominal", "scale": {"range": ["#78c679", "#ff5722", "#bdbdbd"]}},
"opacity": {"value": 0.8},
"tooltip": [
{"field": "Task", "type": "nominal", "title": "Task"},
{"field": "StartDate", "type": "temporal", "title": "Start"},
{"field": "EndDate", "type": "temporal", "title": "End"}
]
}
}
],
"transform": [
{
"calculate": "datum.height*step",
"as": "chartHeight"
},
{
"calculate": "if(datum.chartHeight<200, 200, if(datum.chartHeight>500, 500, datum.chartHeight))",
"as": "dynamicHeight"
}
],
"height": {"field": "dynamicHeight"}
}
以上Vega-Lite代码将甘特图高度设置为自适应的动态高度,具体操作步骤如下:
1.在encoding中按照甘特图的常规方式设置y、x、x2的值;
2.在layer.mark中通过设置height的值为step的倍数来调整每个甘特图块的高度;
3.在transform中计算出甘特图的实际高度chartHeight,并根据需求进行条件判断来获得动态高度dynamicHeight,最后将dynamicHeight绑定到甘特图的height中即可。
需要注意的是,由于甘特图的高度是通过动态计算得出的,所以在进行条件判断时需要根据实际情况设定阈值。