Text wrapping in Vega JS Charts (SVG and Canvas)

Gramener
2 min readMay 6, 2020

--

Creating a Bar Chart using Vega JS library is shown here.
https://vega.github.io/vega/tutorials/bar-chart/

The sample data in the above tutorial has alphabets as Labels. In the real-world, data labels can be lengthy. For example, a bar chart showing sales of various products.

"data": [
{
"name": "table",
"values": [
{"category": "Meat and Seafood", "amount": 28},
{"category": "Milk and milk products", "amount": 55},
{"category": "Ice cream", "amount": 43},
{"category": "Cereals and Breakfast Foods", "amount": 91},
{"category": "Nuts and seeds", "amount": 81},
{"category": "Seasoning and spices", "amount": 53},
{"category": "Sweets, candy, chocolate", "amount": 19},
{"category": "Thin crispy breads", "amount": 87}
]
}
],

Replacing with the above product data in the example tutorial would render the below bar chart.

A simple way to remove the overlapping of labels is to rotate the labels by an angle.

"axes": [
{ "orient": "bottom", "scale": "xscale", "labelAngle": -45 },
{ "orient": "left", "scale": "yscale" }
],

To rotate x-axis labels, labelAngle property is used in the code snippet.

The labels no more overlap with neighboring labels but are overlapping with bars.

text type mark documentation mentions a solution to wrap text.

*text property*

The text to display. This text may be truncated if the rendered length of the text exceeds the limit parameter.
For versions ≥ 5.7, a string array specifies multiple lines of text.

When x-axis vega config is written such that labels text is an array, each item in the array is rendered in a single line.

"axes": [
{ "orient": "bottom", "scale": "xscale",
"encode": {
"labels": {
"update": {
"text": {"signal": "split(datum.value, ' ')"}
}
}
}

},
{ "orient": "left", "scale": "yscale" }
],

By default, vega gets the labels on the x-axis from the field mentioned in the definition of xscale. To transform the labels, encode block is used.

split(datum.value, ' ') results in an array and each item in the array is on a single line.

Originally published by Tejesh P. at https://dev.to on May 6, 2020.

--

--

Gramener

Gramener is a design-led data science company that solves complex business problems with compelling data stories using insights and a low-code platform, Gramex.