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 real-world, data labels can be long. 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 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 about 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 x-axis from the field mentioned in 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.
Top comments (1)
Thanks for the example, I'm wondering, is there a way to split every two words?