Automatically adjust maximum width of PieChart labels base on available space
This demo shows how we can use events to automatically update maxWidth for truncated slices labels to fit into available space.
/** * --------------------------------------- * This demo was created using amCharts 5. * * For more information visit: * https://www.amcharts.com/ * * Documentation is available at: * https://www.amcharts.com/docs/v5/ * --------------------------------------- */
// Create root and chartvar root = am5.Root.new("chartdiv");
root.setThemes([am5themes_Animated.new(root)]);
var chart = root.container.children.push( am5percent.PieChart.new(root, { layout: root.verticalLayout }));
// Define datavar data = [ { country: "France", sales: 100000 }, { country: "Spain", sales: 160000 }, { country: "United Kingdom", sales: 80000 }];
// Create seriesvar series = chart.series.push( am5percent.PieSeries.new(root, { name: "Series", valueField: "sales", categoryField: "country" }));
// Ensure that labels allways fitseries.labels.template.setAll({ oversizedBehavior: "truncate"});
series.onPrivate("width", function (width) { const maxWidth = (width - series.getPrivate("radius") * 2) / 2; series.labels.template.set("maxWidth", maxWidth);});
series.data.setAll(data);
// Add legendvar legend = chart.children.push( am5.Legend.new(root, { centerX: am5.percent(50), x: am5.percent(50), layout: root.horizontalLayout }));
legend.data.setAll(series.dataItems);<div id="chartdiv"></div>body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";}
#chartdiv { width: 100%; height: 95vh;}{ "type": "PieChart", "settings": { "layout": { "type": "VerticalLayout" } }, "properties": { "series": [ "#series-0" ] }, "children": [ { "type": "Legend", "settings": { "centerX": { "type": "Percent", "value": 50 }, "x": { "type": "Percent", "value": 50 }, "layout": { "type": "HorizontalLayout" } }, "properties": { "data": "#series-0.dataItems" } } ], "refs": [ { "data-0": [ { "country": "France", "sales": 100000 }, { "country": "Spain", "sales": 160000 }, { "country": "United Kingdom", "sales": 80000 } ] }, { "series-0": { "type": "PieSeries", "settings": { "name": "Series", "valueField": "sales", "categoryField": "country" }, "properties": { "data": "#data-0", "labels": { "properties": { "template": { "settings": { "oversizedBehavior": "truncate", "maxWidth": 122 } } } } } } } ]}automatically-adjust-maximum-width-of-piechart-labels-base-o