Back to skills
SkillHub ClubAnalyze Data & AIFrontendData / AI

G2 Legend Expert

Provides detailed knowledge of G2 chart library's legend rendering system, including component inference, layout calculation, and interaction handling. Explains why manual padding changes legend height and offers concrete solutions. Useful for developers customizing or debugging G2 legends.

Packaged view

This page reorganizes the original catalog entry around fit, installability, and workflow context first. The original raw source lives below.

Stars
12,527
Hot score
99
Updated
March 20, 2026
Overall rating
A8.4
Composite score
7.4
Best-practice grade
N/A

Install command

npx @skill-hub/cli install antvis-g2-g2-legend-expert
data-visualizationg2-chartslegend-configurationlayout-debuggingchart-customization

Repository

antvis/G2

Skill path: .claude/skills/g2-legend-expert

Provides detailed knowledge of G2 chart library's legend rendering system, including component inference, layout calculation, and interaction handling. Explains why manual padding changes legend height and offers concrete solutions. Useful for developers customizing or debugging G2 legends.

Open repository

Best for

Primary workflow: Analyze Data & AI.

Technical facets: Frontend, Data / AI.

Target audience: G2 chart library developers implementing custom legends, debugging layout issues, or extending legend functionality.

License: Unknown.

Original source

Catalog source: SkillHub Club.

Repository owner: antvis.

This is still a mirrored public skill entry. Review the repository before installing into production workflows.

What it helps with

  • Install G2 Legend Expert into Claude Code, Codex CLI, Gemini CLI, or OpenCode workflows
  • Review https://github.com/antvis/G2 before adding G2 Legend Expert to shared team environments
  • Use G2 Legend Expert for frontend workflows

Works across

Claude CodeCodex CLIGemini CLIOpenCode

Favorites: 1.

Sub-skills: 0.

Aggregator: No.

Original source / Raw SKILL.md

---
name: G2 Legend Expert
description: Expert skill for G2 legend development - provides comprehensive knowledge about legend rendering implementation, component architecture, layout algorithms, and interaction handling. Use when implementing, customizing, or debugging legend functionality in G2 visualizations.
---

# G2 Legend Expert Skill

## Overview

This skill provides comprehensive knowledge about legend rendering in G2, covering the complete legend rendering flow from component creation to layout calculation and interaction handling.

## Legend Rendering Flow in G2

The legend rendering flow in G2 follows a multi-stage process that transforms legend configuration into visual components. This flow involves several key stages:

### 1. Legend Component Inference

Legend components are inferred from the chart's scales and configuration during the initial setup phase. The inference process is handled by the `inferComponent` function in `src/runtime/component.ts`:

- **Scale Analysis**: The system analyzes all scales in the chart, looking for channels like `shape`, `size`, `color`, and `opacity`
- **Legend Type Detection**: Based on the scale types, the system determines whether to create `legendCategory` (for discrete scales) or `legendContinuous` (for continuous scales)
- **Position Inference**: Default positions and orientations are inferred based on the chart type and coordinate system

### 2. Legend Component Creation

Two main legend component types are implemented:

#### LegendCategory

Located in `src/component/legendCategory.ts`, this component handles categorical legends:

- **Data Processing**: Processes domain values from scales to create legend items
- **Marker Inference**: Automatically infers appropriate markers based on the chart's shapes and scales
- **Layout Wrapper**: Uses `LegendCategoryLayout` to handle layout positioning
- **Rendering Options**: Supports both standard GUI rendering and custom HTML rendering via the `render` option

#### LegendContinuous

Located in `src/component/legendContinuous.ts`, this handles continuous legends:

- **Scale Type Handling**: Supports various continuous scale types including linear, log, time, quantize, quantile, and threshold
- **Configuration Inference**: Generates appropriate configuration based on scale properties
- **Ribbon Generation**: Creates color ribbons for continuous scales
- **Label Formatting**: Handles proper formatting of continuous scale labels

### 3. Layout and Sizing Calculation

The layout process is managed in `src/runtime/layout.ts` and involves several critical steps:

#### Component Size Computation

The `computeComponentSize` function handles sizing based on component type:

- **Auto vs Manual Padding**: When padding is set to 'auto', the system dynamically calculates component size based on content. When manually set, it uses default sizes.
- **Size Calculation**: Different calculation strategies for different component types (axis, legend, title, etc.)
- **Cross-size Considerations**: Takes into account cross-size dimensions for proper layout

#### Padding Calculation Logic

The core layout logic is in the `computePadding` function:

```typescript
const autoSizeOf = (d) => {
  if (d.size) return;
  if (value !== 'auto') sizeOf(d);
  else {
    // Compute component size dynamically
    computeComponentSize(
      d,
      crossSize,
      crossPadding,
      position,
      theme,
      library,
    );
    defaultSizeOf(d);
  }
};
```

- **Auto Padding ('auto')**: Calls `computeComponentSize` to measure actual content dimensions
- **Manual Padding**: Uses `defaultSize` directly, bypassing content measurement

### 4. Component Rendering

The `renderComponent` function in `src/runtime/component.ts` handles the actual rendering:

- **Component Instantiation**: Creates the appropriate component based on type
- **Context Injection**: Provides scale instances, theme, and other context information
- **Display Object Creation**: Returns a DisplayObject that can be added to the chart

### 5. Legend Positioning and BBox Assignment

After size calculation, the `placeComponents` function assigns bounding boxes:

- **Position-based Grouping**: Components are grouped by position (top, bottom, left, right, center)
- **Area Calculation**: Each position gets a specific area in the chart layout
- **Dimension Assignment**: Components receive their final x, y, width, and height values

## Legend Types and Configuration

### Categorical Legends

Categorical legends (LegendCategory) are used for discrete scales and support:

- **Item Markers**: Automatic marker generation based on chart types
- **Flexible Layouts**: Supports both flex and grid layouts
- **Custom Rendering**: HTML-based custom rendering via the `render` option
- **Interaction Features**: Support for filtering and focus modes

### Continuous Legends

Continuous legends (LegendContinuous) handle continuous scales:

- **Color Ranges**: Support for various color interpolation methods
- **Scale Types**: Handles linear, log, time, and quantile scales
- **Threshold Handling**: Special support for threshold scales with custom boundaries
- **Size Control**: Configurable ribbon sizes and label spacing

## Interaction Handling

### Legend Filtering

The legend filtering interaction is implemented in `src/interaction/legendFilter.ts`:

- **Event Delegation**: Handles click, pointerenter, and pointerout events
- **State Management**: Maintains selection states and visual feedback
- **Filter Propagation**: Updates chart data based on legend selections
- **Cross-chart Coordination**: Supports filtering across multiple chart views

### Visual States

Legends support multiple visual states:

- **Selected/Unselected**: Visual distinction between selected and unselected items
- **Hover States**: Pointer interaction feedback
- **Focus Mode**: Special highlighting for focused items

## Customization and Theming

### Theme Integration

Legend components integrate with G2's theming system:

- **Theme Properties**: Respects theme settings for colors, fonts, and spacing
- **Component-specific Themes**: Separate theme settings for different legend types
- **Style Override**: Allows specific style overrides via component options

### Layout Customization

- **Position Control**: Configurable positions (top, bottom, left, right, center)
- **Size Control**: Manual or automatic size calculation
- **Padding Control**: Configurable padding and spacing
- **Orientation Control**: Horizontal or vertical orientation options

## Best Practices

### Performance Considerations

- **Efficient Data Processing**: Minimize legend data processing for large datasets
- **Optimized Rendering**: Use appropriate rendering strategies for different legend types
- **Event Handling**: Properly manage and clean up event listeners

### Accessibility

- **Label Clarity**: Ensure legend labels are clear and descriptive
- **Color Contrast**: Maintain sufficient contrast for color accessibility
- **Interaction Feedback**: Provide clear visual feedback for interactions

## Troubleshooting Common Issues

### Layout Issues

When `paddingTop` is manually set (e.g., `paddingTop: 72`), the height of `legendCategory` changes unexpectedly (e.g., from 60px to 40px). This occurs because:

1. When padding is manually set, the layout engine uses the component's `defaultSize` instead of measuring actual content
2. For `LegendCategory`, the default size is 40 (defined in `src/component/legendCategory.ts`)
3. To fix this, explicitly set the `size` property in the legend configuration to override the default

### Interaction Issues

- **Event Bubbling**: Ensure proper event handling to prevent unwanted interactions
- **State Synchronization**: Keep legend states synchronized across different chart views
- **Performance**: Use throttling for filter events to prevent excessive updates

## References

For more detailed information on legend layout mechanisms and related topics, see the knowledge directory:

- **Legend Layout Mechanisms**: `./knowledge/legendLayout.md` - Detailed analysis of padding behavior and layout calculations
  - Manual Padding Effects: How manually set padding values affect legend sizing
  - Default Size Fallback: Behavior when padding is set manually vs. 'auto'
  - Layout Calculation Logic: The core algorithm in `computePadding` function


---

## Referenced Files

> The following files are referenced in this skill and included for context.

### knowledge/legendLayout.md

```markdown
# Legend Layout Mechanism with Manual Padding

## Problem Description
When `paddingTop` is manually set (e.g., `paddingTop: 72`), the height of `legendCategory` changes unexpectedly (e.g., from 60px to 40px).

## Cause Analysis

### 1. Layout Calculation Logic
G2's layout engine (located in `src/runtime/layout.ts`) adopts different strategies when calculating component dimensions based on the `padding` configuration. The core logic resides in the `computePadding` function:

```typescript
// src/runtime/layout.ts

const autoSizeOf = (d) => {
  if (d.size) return; // If component already has a size, return immediately
  
  // Key logic: If padding is not 'auto' (i.e., manually set value), use default size
  if (value !== 'auto') sizeOf(d); 
  else {
    // If padding is 'auto', dynamically calculate component size
    computeComponentSize(
      d,
      crossSize,
      crossPadding,
      position,
      theme,
      library,
    );
    defaultSizeOf(d);
  }
};
```

- **`value === 'auto'` (Default)**: Calls `computeComponentSize`, which measures the actual content of the component (text, icons, etc.) to calculate the precise required height (e.g., 60px).
- **`value !== 'auto'` (Manual setting, e.g., 72)**: Calls `sizeOf(d)`.

### 2. Fallback Mechanism (`sizeOf`)
When entering the `sizeOf` branch, the code directly uses the component's `defaultSize`:

```typescript
// src/runtime/layout.ts

const sizeOf = (d) => {
  if (d.type === 'group') {
    // ...handle grouping...
  } else {
    d.size = d.defaultSize; // <--- Directly assign defaultSize
  }
};
```

In `src/component/legendCategory.ts`, the default size of `LegendCategory` is defined as **40**:

```typescript
// src/component/legendCategory.ts
LegendCategory.props = {
  defaultPosition: 'top',
  // ...
  defaultSize: 40, // <--- Default height
  // ...
};
```

Therefore, when you set `paddingTop: 72`, the layout engine assumes you have taken over space allocation. To avoid redundant calculations or conflicts, it no longer measures the actual content height of the legend but directly falls back to the default value of 40px.

## Solution

If you need to fix `paddingTop` but also want to maintain a specific legend height (e.g., 60px), you must explicitly set the `size` property in the legend configuration. The explicitly set `size` has the highest priority and will be adopted immediately in the first line of `autoSizeOf`: `if (d.size) return;`.

```javascript
chart.options({
  // ...
  paddingTop: 72, // 1. Manually set padding
  legend: {
    color: {
      size: 60,   // 2. Explicitly set height to prevent fallback to default value (40)
      // ...
    },
  },
});
```

```

G2 Legend Expert | SkillHub