Created
March 14, 2021 01:38
-
-
Save kurtismash/346d0492fa4360a9a000e9ecee8ea31c to your computer and use it in GitHub Desktop.
Vertically center multiline text marks using Vega
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// As a fix for https://github.com/vega/vega/issues/2057 is still not released | |
// I needed a workaround for vertically centering multiline text. This method | |
// explicitly sets the lineHeight of the text mark which can then be used to | |
// calculate the offset needed to shift the anchor point of the text on the y | |
// axis. The vertical centering is applied by the marks[0].transform[0] formula. | |
{ | |
"$schema": "https://vega.github.io/schema/vega/v5.json", | |
"data": [ | |
{ | |
"name": "labels", | |
"values": [ | |
{"x": 0, "text": "Line 1"}, | |
{"x": 50, "text": "Line 1/Line 2"}, | |
{"x": 100, "text": "Line 1/Line 2/Line 3"}, | |
{"x": 150, "text": "Line 1/Line 2/Line 3/Line 4"}, | |
{"x": 200, "text": "Line 1/Line 2/Line 3/Line 4/Line 5"} | |
] | |
} | |
], | |
"marks": [ | |
{ | |
"type": "text", | |
"from": {"data": "labels"}, | |
"encode": { | |
"enter": { | |
"text": {"field": "text"}, | |
"x": { | |
"field": "x" | |
}, | |
"y": { | |
"value": 20 | |
}, | |
"font": {"value": "Helvetica"}, | |
"lineBreak": {"value": "/"}, | |
"lineHeight": {"value": 30} | |
} | |
}, | |
"transform": [ | |
{ | |
"type": "formula", | |
"expr": "-datum.lineHeight*length(split(datum.text, datum.lineBreak))/2", | |
"as": "dy" | |
} | |
] | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment