Imagine if you could visualize your data in a structured chart like this:
"values": [
{"id": "1", "parent": null, "title": "Animal"},
{"id": "2", "parent": "1", "title": "Duck"},
{"id": "3", "parent": "1", "title": "Fish"},
{"id": "4", "parent": "1", "title": "Zebra"}
]
Once you have your nodes arranged in a tree-like layout using the stratify
function:
"transform": [
{
"type": "stratify",
"key": "id",
"parentKey": "parent"
},
{
"type": "tree",
"method": "tidy",
"separation": true,
"size": [{"signal": "width"}, {"signal": "height"}]
}
]
For creating connecting lines between nodes, use treelinks
along with linkpath
to generate them:
{
"name": "links",
"source": "tree",
"transform": [
{ "type": "treelinks" },
{ "type": "linkpath",
"shape": "diagonal"
}
]
}
Next step is to represent the data visually using marks in Vega. Here, I'm keeping it simple by drawing rectangles and text labels for each node:
"marks": [
{
"type": "path",
"from": {"data": "links"},
"encode": {
"enter": {
"path": {"field": "path"}
}
}
},
{
"type": "rect",
"from": {"data": "tree"},
"encode": {
"enter": {
"stroke": {"value": "black"},
"width": {"value": 100},
"height": {"value": 20},
"x": {"field": "x"},
"y": {"field": "y"}
}
}
},
{
"type": "text",
"from": {"data": "tree"},
"encode": {
"enter": {
"stroke": {"value": "black"},
"text": {"field": "title"},
"x": {"field": "x"},
"y": {"field": "y"},
"dx": {"value":50},
"dy": {"value":13},
"align": {"value": "center"}
}
}
}
]
}
While the output might not match exactly, this basic setup provides an approximation of your target visualization. To render different shapes for root and leaf nodes, you can apply filters on the dataset and adjust the mark types accordingly:
{
"name": "tree-boxes",
"source": "tree",
"transform": [
{
"type": "filter",
"expr": "datum.parent == null"
}
]
},
{
"name": "tree-circles",
"source": "tree",
"transform": [
{
"type": "filter",
"expr": "datum.parent != null"
}
]
},
{
"type": "rect",
"from": {"data": "tree-boxes"},
"encode": {
"enter": {
"stroke": {"value": "black"},
"width": {"value": 100},
"height": {"value": 20},
"x": {"field": "x"},
"y": {"field": "y"}
}
}
},
{
"type": "symbol",
"from": {"data": "tree-circles"},
"encode": {
"enter": {
"stroke": {"value": "black"},
"width": {"value": 100},
"height": {"value": 20},
"x": {"field": "x"},
"y": {"field": "y"}
}
}
}