堆叠柱状图图例自定义:将分组图例命名为Location 1等
Solution: Rename Legend Groups to Location Names in Stacked Bar Chart
To rename your legend groups from default stack names (like "unattended") to "Location 1", "Location 2", etc., while keeping your linkedTo:previous grouping intact, follow these steps:
- Create a stack-to-location mapping: Define a lookup object to link internal stack identifiers to your friendly location names.
- Customize the legend label formatter: Use this mapping to replace default legend text with your desired location names.
- Update tooltips (optional): Ensure location names appear in tooltips for consistent user experience.
Here's a complete, working code example:
// Map stack IDs to your desired location names const stackToLocation = { loc1: "Location 1", loc2: "Location 2", loc3: "Location 3" // Add more entries as needed }; Highcharts.chart('container', { chart: { type: 'bar' }, title: { text: 'Attendance Breakdown by Location' }, xAxis: { categories: ['Event 1', 'Event 2', 'Event 3'] }, yAxis: { min: 0, title: { text: 'Total Participants' }, stackLabels: { enabled: true, formatter: function() { // Show location name in stack totals (optional) return stackToLocation[this.stack] || this.stack; } } }, legend: { labelFormatter: function() { // Only format the primary series in each stack (linkedTo: null) if (!this.options.linkedTo) { return stackToLocation[this.options.stack] || this.name; } return ''; // Hide labels for linked series (handled by linkedTo, but safe to include) } }, tooltip: { formatter: function() { const location = stackToLocation[this.series.options.stack] || this.series.options.stack; return `<b>${location}</b><br/>` + `${this.series.name}: ${this.y}<br/>` + `Total: ${this.point.stackTotal}`; } }, plotOptions: { series: { stacking: 'normal', linkedTo: ':previous' // Keep your grouping logic } }, series: [ // Location 1 stack { name: 'Attended', data: [15, 22, 18], stack: 'loc1', linkedTo: null }, { name: 'Unattended', data: [5, 8, 7], stack: 'loc1' }, // Location 2 stack { name: 'Attended', data: [12, 19, 25], stack: 'loc2', linkedTo: null }, { name: 'Unattended', data: [8, 11, 5], stack: 'loc2' } ] });
Key Notes:
- Stack Mapping: The
stackToLocationobject makes it easy to update location names without modifying your core series data. - Legend Logic: We target only the primary series in each stack (
linkedTo: null) since linked series are hidden from the legend automatically. This ensures each legend entry corresponds to a location group. - Consistent Naming: Extending the mapping to tooltips and stack labels ensures users see the same location name across all parts of the chart.
内容的提问来源于stack exchange,提问作者BN83
相关产品推荐
相关产品推荐

