动态加载数据时Highcharts出现多余图例的问题及解决方案咨询
Hey there! Let's break down why you're seeing that extra legend item and go through solid solutions to get your charts working as expected.
The Root Cause
Your initialization code includes an empty object { } in the series array. Highcharts treats this as a valid (though empty) series, so it automatically adds a blank legend item for it—that's your extra legend right there.
Solution 1: Initialize with an Empty Series Array (Cleanest Approach)
Instead of adding an empty series upfront, start with an empty (or omitted) series array, then dynamically add your actual data series using addSeries. This eliminates the extra legend entirely.
Here's the updated code:
$(function () { // Initialize chart without any pre-existing empty series chart = Highcharts.chart('container', { // Keep your other configuration options here (title, xAxis, etc.) // series defaults to an empty array if not specified }); // Your actual dataset const dataa = [ { "name": "Unit Test 1", "data":[1,13,15,17,40,50,80] }, { "name": "Unit Test 2", "data":[2,20,50,40,20,50,15] }, { "name": "Unit Test 3", "data":[3,50,40,10,30,40,25] } ]; // Loop through your data and add each series dataa.forEach(seriesData => { chart.addSeries(seriesData); }); });
Solution 2: Hide the Empty Initial Series (If You Need to Keep It)
If for some reason you have to retain that initial empty series (e.g., placeholder logic), you can disable its legend entry with the showInLegend property:
$(function () { chart = Highcharts.chart('container', { series: [ { showInLegend: false, // Prevent this empty series from appearing in the legend data: [] // Explicitly set empty data to avoid potential rendering issues } ] }); // Add your actual series as before const dataa = [/* Your dataset */]; dataa.forEach(seriesData => { chart.addSeries(seriesData); }); });
Bonus: Initialize with Full Series Data (If Possible)
If your dataa dataset is available when the chart initializes (no need for async loading), you can skip addSeries entirely and pass the data directly to the chart constructor. This is more efficient than adding series one by one:
$(function () { const dataa = [/* Your dataset */]; chart = Highcharts.chart('container', { series: dataa // Pass the full dataset directly }); });
Key Takeaway
The extra legend is caused by that empty initial series entry. Removing it (Solution 1) is the most straightforward fix, but the other options work if you have specific constraints. Using addSeries is totally valid for dynamic data—just make sure you're not adding unintended empty series upfront!
内容的提问来源于stack exchange,提问作者Gvs Akhil

