如何在多个饼图 amcharts 4 上制作自定义图例?

How to make custom legends on multiple pie charts amcharts 4?

假设我们有一个饼图,如下代码所示:

    am4core.ready(function() {
        // Create chart instance
        chartReg[id] = am4core.create(id, am4charts.PieChart);

        // Add data
        chartReg[id].data = data;
        chartReg[id].innerRadius = 60;

        // Add and configure Series
        var pieSeries = chartReg[id].series.push(new am4charts.PieSeries());
        pieSeries.dataFields.value = "value";
        pieSeries.dataFields.category = "key";


        pieSeries.ticks.template.disabled = true;
        pieSeries.alignLabels = false;

        // Create custom legend
        chartReg[id].events.on("ready", function(event) {
            // populate our custom legend when chart renders
            chartReg[id].customLegend = $('#legend');
            pieSeries.dataItems.each(function(row, i) {
            var color = pieSeries.colors.getIndex(i);
            var percent = Math.round(row.values.value.percent * 100) / 100;
            var value = row.value;
            var title = row.category 
            legend.innerHTML += '<div class="legend-item" id="legend-item-' + i + '" onclick="toggleSlice(' + i + ');" onmouseover="hoverSlice(' + i + ');" onmouseout="blurSlice(' + i + ');"><div class="legend-marker" style="background: ' + color + '"></div><div class="legend-title">' + title + '</div><div class="legend-value">' + value + ' | ' + percent + '%</div></div>';
            });
        });         
    });

自定义图例工作正常,如下所示:

但是如果我们有多个饼图同时在 DOM 中呈现,则图例不会显示!

❤❤ 感谢您阅读我的问题。 ❤❤

我找到了答案。代表:

legend.innerHTML += '<div>...</div>';

我们应该使用:

$('#legend_'+id).append('<div>...</div>');

将图例动态添加到相关 div ;)