Handling long category axis labels
This tutorial looks at ways on how to handle situations where labels of a CategoryAxis are too long to comfortably fit.
Wrapping or truncating
Section titled “Wrapping or truncating”This sections shows how we can use an event and oversizeBehavior on axis labels, to make them auto-wrap automatically.
// Rendererlet xRenderer = am5xy.AxisRendererX.new(root, { minGridDistance: 30});
// Axislet xAxis = chart.xAxes.push(am5xy.CategoryAxis.new(root, { maxDeviation: 0.3, categoryField: "country", renderer: xRenderer, tooltip: am5.Tooltip.new(root, {})}));
// Enable label wrappingxRenderer.labels.template.setAll({ oversizedBehavior: "wrap", textAlign: "center"});
// Automatically set maxWidth on labels when it changes on an axisxAxis.onPrivate("cellWidth", function(cellWidth) { xRenderer.labels.template.set("maxWidth", cellWidth)});// Renderervar xRenderer = am5xy.AxisRendererX.new(root, { minGridDistance: 30});
// Axisvar xAxis = chart.xAxes.push(am5xy.CategoryAxis.new(root, { maxDeviation: 0.3, categoryField: "country", renderer: xRenderer, tooltip: am5.Tooltip.new(root, {})}));
// Enable label wrappingxRenderer.labels.template.setAll({ oversizedBehavior: "wrap", textAlign: "center"});
// Automatically set maxWidth on labels when it changes on an axisxAxis.onPrivate("cellWidth", function(cellWidth) { xRenderer.labels.template.set("maxWidth", cellWidth)});The above code uses axis’ event of cellWidth (which reports whenever cell width is changed) to apply actual maxWidth setting to the labels template. oversizedBehavior: "wrap" uses maxWidth to automatically wrap labels.
Similarly, we can also make labels truncate by using oversizedBehavior: "truncate" (instead of "wrap").
xRenderer.labels.template.setAll({ oversizedBehavior: "truncate", textAlign: "center"});xRenderer.labels.template.setAll({ oversizedBehavior: "truncate", textAlign: "center"});Auto-rotating labels
Section titled “Auto-rotating labels”Another option is to automatically rotate labels when certain threshold of axis’ cell width is reached.
// Automatically rotate all labels if at least one of them// does not fit into certain widthxAxis.onPrivate("cellWidth", function(cellWidth) { let rotated = false; xRenderer.labels.each(function(label) { if (label.width() > cellWidth) { rotated = true; } });
if (rotated) { xRenderer.labels.template.setAll({ rotation: -45, centerX: am5.p100 }); } else { xRenderer.labels.template.setAll({ rotation: 0, centerX: am5.p50 }); }});// Automatically rotate all labels if at least one of them// does not fit into certain widthxAxis.onPrivate("cellWidth", function(cellWidth) { var rotated = false; xRenderer.labels.each(function(label) { if (label.width() > cellWidth) { rotated = true; } });
if (rotated) { xRenderer.labels.template.setAll({ rotation: -45, centerX: am5.p100 }); } else { xRenderer.labels.template.setAll({ rotation: 0, centerX: am5.p50 }); }});