Re-arranging elements of the chart legend
This demo shows how we can use legend item label’s parentset event to move it before the marker.
Open in:New tab
/** * --------------------------------------- * This demo was created using amCharts 4. * * For more information visit: * https://www.amcharts.com/ * * Documentation is available at: * https://www.amcharts.com/docs/v4/ * --------------------------------------- */
// Themes beginam4core.useTheme(am4themes_animated);// Themes end
// Create chart instancevar chart = am4core.create("chartdiv", am4charts.PieChart);
// Add and configure Seriesvar pieSeries = chart.series.push(new am4charts.PieSeries());pieSeries.dataFields.value = "litres";pieSeries.dataFields.category = "country";
// Let's cut a hole in our Pie chart the size of 30% the radiuschart.innerRadius = am4core.percent(30);
// Put a thick white border around each SlicepieSeries.slices.template.stroke = am4core.color("#fff");pieSeries.slices.template.strokeWidth = 2;pieSeries.slices.template.strokeOpacity = 1;// change the cursor on hover to make it apparent the object can be interacted withpieSeries.slices.template.cursorOverStyle = [ { property: "cursor", value: "pointer" }];
pieSeries.alignLabels = false;pieSeries.labels.template.bent = true;pieSeries.labels.template.radius = 3;pieSeries.labels.template.padding(0, 0, 0, 0);
pieSeries.ticks.template.disabled = true;
// Create a base filter effect (as if it's not there) for the hover to return tovar shadow = pieSeries.slices.template.filters.push(new am4core.DropShadowFilter());shadow.opacity = 0;
// Create hover statevar hoverState = pieSeries.slices.template.states.getKey("hover"); // normally we have to create the hover state, in this case it already exists
// Slightly shift the shadow and make it more prominent on hovervar hoverShadow = hoverState.filters.push(new am4core.DropShadowFilter());hoverShadow.opacity = 0.7;hoverShadow.blur = 5;
// Add a legendchart.legend = new am4charts.Legend();chart.legend.position = "right";chart.legend.markers.template.children.getIndex(0).cornerRadius(30, 30, 30, 30);chart.legend.labels.template.textAlign = "end";chart.legend.labels.template.events.on("parentset", function (event) { event.target.toBack();});
chart.data = [ { country: "Lithuania", litres: 501.9 }, { country: "Germany", litres: 165.8 }, { country: "Australia", litres: 139.9 }, { country: "Austria", litres: 128.3 }, { country: "UK", litres: 99 }, { country: "Belgium", litres: 60 }];<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: 500px;}re-arranging-elements-of-the-chart-legend