Text wrapping in Vega JS Charts (SVG and Canvas)

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.

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.

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.

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.

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 is a design-led data science company that solves complex business problems with compelling data stories using insights and a low-code platform, Gramex.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
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.