logo

G2

  • Chart Gallery
  • Docs
  • Examples
  • Theme
  • Ecosystem
  • Productsantv logo arrow
  • 5.3.3
  • Get Started
  • Introduction
    • What is G2
    • Using in Frontend Frameworks
    • Experimental Spec API
  • Chart API
  • Core Concepts
    • Chart
      • Components of G2 Charts
      • How to Use Charts
    • Mark
      • Overview
      • area
      • box
      • boxplot
      • cell
      • chord
      • density
      • gauge
      • heatmap
      • image
      • interval
      • line
      • lineX
      • lineY
      • link
      • liquid
      • sunburst
      • point
      • polygon
      • range
      • rangeX
      • rangeY
      • rect
      • shape
      • text
      • vector
      • connector
      • wordCloud
    • View
    • Data
      • Overview
      • custom
      • ema
      • fetch
      • filter
      • fold
      • inline
      • join
      • kde
      • log
      • map
      • pick
      • rename
      • slice
      • sort
      • sortBy
    • Encode
    • Scale
      • Overview
      • band
      • linear
      • log
      • ordinal
      • point
      • quantile
      • quantize
      • sqrt
      • threshold
      • time
      • pow
    • Transform
      • Overview
      • bin
      • binX
      • diffY
      • dodgeX
      • flexX
      • group
      • groupColor
      • groupX
      • groupY
      • jitter
      • jitterX
      • jitterY
      • normalizeY
      • pack
      • sample
      • select
      • selectX
      • selectY
      • sortColor
      • sortX
      • sortY
      • stackEnter
      • stackY
      • symmetryY
    • Coordinate
      • Overview
      • fisheye
      • parallel
      • polar
      • theta
      • transpose
      • radial
      • cartesian3D
      • helix
    • Style
    • Animate
      • Overview
      • fadeIn
      • fadeOut
      • growInX
      • growInY
      • morphing
      • pathIn
      • scaleInX
      • scaleInY
      • scaleOutX
      • scaleOutY
      • waveIn
      • zoomIn
      • zoomOut
    • State
    • Interaction
      • Overview
      • brushAxisHighlight
      • brushHighlight
      • brushXHighlight
      • brushYHighlight
      • brushFilter
      • brushXFilter
      • brushYFilter
      • chartIndex
      • elementHighlight
      • elementHighlightByColor
      • elementHighlightByX
      • elementSelect
      • elementSelectByColor
      • elementSelectByX
      • legendFilter
      • legendHighlight
      • poptip
      • scrollbarFilter
      • sliderFilter
      • fisheye
    • Composition
      • Overview
      • facetCircle
      • facetRect
      • repeatMatrix
      • spaceFlex
      • spaceLayer
      • timingKeyframe
    • Theme
      • Overview
      • academy
      • classic
      • classicDark
    • Events
    • Color Mapping
  • Chart Component
    • Title
    • Axis
    • Legend
    • Scrollbar
    • Slider
    • Tooltip
    • Data Label
  • Extra Topics
    • Graph
      • forceGraph
      • pack
      • sankey
      • tree
      • treemap
    • Geo
      • geoPath
      • geoView
    • 3D
      • Draw 3D Chart
      • point3D
      • line3D
      • interval3D
      • surface3D
    • Plugin
      • renderer
      • rough
      • lottie
      • a11y
    • Package on demand
    • Set pattern
    • Server-Side Rendering (SSR)
    • Spec Function Expression Support (Available in 5.3.0)
  • Whats New
    • New Version Features
    • Migration from v4 to v5
  • Frequently Asked Questions (FAQ)

Legend

Previous
Axis
Next
Scrollbar

Resources

Ant Design
Galacea Effects
Umi-React Application Framework
Dumi-Component doc generator
ahooks-React Hooks Library

Community

Ant Financial Experience Tech
seeconfSEE Conf-Experience Tech Conference

Help

GitHub
StackOverflow

more productsMore Productions

Ant DesignAnt Design-Enterprise UI design language
yuqueYuque-Knowledge creation and Sharing tool
EggEgg-Enterprise-class Node development framework
kitchenKitchen-Sketch Tool set
GalaceanGalacean-互动图形解决方案
xtechLiven Experience technology
© Copyright 2025 Ant Group Co., Ltd..备案号:京ICP备15032932号-38

Loading...

Overview

In G2, Legend is an auxiliary element of the chart that uses color, size, and shape to distinguish different data types and is used for data filtering in charts. It can be understood as the visualization of scales corresponding to non-spatial channels (color, opacity, size, shape). G2 automatically generates different legends based on the set graphic attribute mappings and data types. When a variable corresponds to multiple graphic attributes, G2 merges the legends to achieve simplification.

The four non-spatial channels color, opacity, size, and shape automatically generate different legends when they receive parameters that are determined to be fields from the data source:

Visual ChannelDescription
colorGenerate legend based on different colors
opacityGenerate legend based on different opacity
sizeGenerate legend based on different sizes
shapeGenerate legend based on different shapes

Components

legend-overview

Usage

There are two ways to configure legends:

First, pass a boolean to set whether to display the legend.

({
type: 'interval',
legend: false; // Hide all legends
})
({
type: 'interval',
legend: {color: false}; // Hide the legend for the color channel
})

Second, pass legendOption to configure the legend as a whole.

({
type: 'interval',
legend: {
color: {},
size: {},
},
});

Configuration Levels

Legends can be configured at the Mark level. In G2, each mark has its own legend. If the scales corresponding to marks are synchronized, the legends are also merged.

({
type: 'interval',
legend: {
color: {},
size: {},
},
});

Legends can also be configured at the View level. Legends have transitivity. Legends declared on a view are passed to the marks declared in children. If the mark has a legend for the corresponding channel, they are merged; otherwise, they don't affect each other.

({
type: 'view',
legend: {
color: {},
size: {},
},
});

Configuration Options

Legends in G2 are divided into continuous legends and categorical legends. Due to the different structures of these two types of legends, their configuration options also differ.

Some configuration options are scoped to categorical legends and continuous legends: Categorical LegendContinuous Legend

PropertyDescriptionTypeDefault ValueRequired
orientationLegend orientation, which is the scroll direction for categorical legendshorizontal | verticalhorizontal
positionPosition of the legendtop | right | left | bottomtop
layoutAdjust the flex layout of the legendlayoutSee layout
sizeSize of the legendnumber-
widthWidth of the legendnumber-
crossPaddingDistance from legend to chart areanumber12
orderOrder of legend in layoutnumber1
titleConfigure legend titletitleSee title
cols Categorical LegendSpecify the number of legend items displayed per row; empty means no limit on columnsnumber-
colPadding Categorical LegendSpecify horizontal spacing between legend itemsnumber12
rowPadding Categorical LegendSpecify vertical spacing between legend itemsnumber8
maxRows Categorical LegendSpecify maximum number of rows for legendnumber3
maxCols Categorical LegendSpecify maximum number of columns for legendnumber3
itemMarker Categorical LegendConfigure legend item markeritemMarkerSee itemMarker
itemLabel Categorical LegendConfigure legend item label textitemLabelSee itemLabel
itemValue Categorical LegendConfigure legend item valueitemValueSee itemValue
itemBackground Categorical LegendConfigure legend item backgrounditemBackgroundSee itemBackground
itemWidth Categorical LegendConfigure legend item widthnumber-
itemSpan Categorical LegendConfigure space allocation for legend item marker, label, and valuenumber | number[][1, 1, 1]
itemSpacing Categorical LegendConfigure spacing between legend item marker, label, and valuenumber | number[][8, 8]
nav Categorical LegendConfigure legend navigatornavSee nav
color Continuous LegendConfigure color band colors for continuous legendstring[] | d3-interpolate-
block Continuous LegendWhether continuous legend displays by intervalsbooleanfalse
type Continuous LegendConfigure type of continuous legendsize |colorcolor
ribbon Continuous LegendConfigure color band of continuous legendribbonSee ribbon
handle Continuous LegendConfigure slider handle of continuous legendhandleSee handle
label Continuous LegendConfigure labels/tick values of continuous legendlabelSee label
indicator Continuous LegendConfigure indicator of continuous legendindicatorSee indicator

orientation

optional horizontal | vertical

Legend orientation, which is the scroll direction for categorical legends. Default is horizontal.

position

optional "top" | "right" | "left" | "bottom"

Position of the legend. Default is top.

(() => {
const positionList = ['top', 'right', 'left', 'bottom'];
const positionMap = positionList.map((p) => {
return {
label: p,
value: p,
};
});
const chart = new G2.Chart();
chart.options({
type: 'interval',
data: [
{ name: 'London', month: 'Jan.', rainfall: 18.9 },
{ name: 'London', month: 'Feb.', rainfall: 28.8 },
{ name: 'London', month: 'Mar.', rainfall: 39.3 },
{ name: 'London', month: 'Apr.', rainfall: 81.4 },
{ name: 'London', month: 'May', rainfall: 47 },
{ name: 'London', month: 'Jun.', rainfall: 20.3 },
{ name: 'London', month: 'Jul.', rainfall: 24 },
{ name: 'London', month: 'Aug.', rainfall: 35.6 },
{ name: 'Berlin', month: 'Jan.', rainfall: 12.4 },
{ name: 'Berlin', month: 'Feb.', rainfall: 23.2 },
{ name: 'Berlin', month: 'Mar.', rainfall: 34.5 },
{ name: 'Berlin', month: 'Apr.', rainfall: 99.7 },
{ name: 'Berlin', month: 'May', rainfall: 52.6 },
{ name: 'Berlin', month: 'Jun.', rainfall: 35.5 },
{ name: 'Berlin', month: 'Jul.', rainfall: 37.4 },
{ name: 'Berlin', month: 'Aug.', rainfall: 42.4 },
],
encode: { x: 'month', y: 'rainfall', color: 'name' },
transform: [{ type: 'dodgeX' }],
});
const handleSetPosition = (position) => {
chart.options({
legend: {
color: {
position,
},
},
});
chart.render(); // Re-render the chart
};
// Insert Position selector
const selectorContainer = document.createElement('div');
selectorContainer.textContent = 'Select legend position ';
const selector = document.createElement('select');
selector.innerHTML = positionMap.map(
(position, index) =>
`<option value="${position.value}" ${index === 0 ? 'selected' : ''}>${
position.label
}</option>`,
);
selector.onchange = (e) => {
handleSetPosition(e.target.value);
};
selectorContainer.appendChild(selector);
const node = chart.getContainer();
node.insertBefore(selectorContainer, node.childNodes[0]);
chart.render();
return node;
})();

layout

LegendLayoutCfg optional

The Legend component supports adjusting its position in the canvas through the layout property. Currently supports basic Flex layout, with supported properties including: justifyContent, alignItems, flexDirection. LegendLayoutCfg configuration is as follows:

PropertyDescriptionTypeDefault ValueRequired
justifyContentMain axis alignmentflex-start | flex-end | centerflex-start
alignItemsCross axis alignmentflex-start | flex-end | centerflex-start
flexDirectionMain axis directionrow | columnrow when position is top and bottom, column for others

By configuring the legend's position and layout, we can flexibly change the legend's position.

// Configure a right-side vertically centered legend
// Step 1: Set position to right
// Step 2: When position is right, the main axis direction flexDirection defaults to column
// Step 3: To achieve vertical centering, we need center alignment in the column direction. Since column is the main axis, configure justifyContent to center
({
legend: {
color: {
position: 'right',
layout: {
justifyContent: 'center',
},
},
},
});

Try it out:

size

number optional

Size of the Legend component. Affects the component's size on the cross axis, e.g., for horizontally positioned legends, it affects the overall height. Manual configuration will cause G2's internal calculation logic to fail, requiring you to configure margin, padding, inset, etc. yourself. See Chart Layout. Not recommended unless customization is needed.

width

number optional

Width of the Legend component.

crossPadding

number optional

Distance between the Legend component and the chart. Default is 12.

order

number optional

Sort order of the Legend component during layout. Default is 1. G2's internal components all have default sort sizes. Smaller values are closer to the chart area. For example, the Title component's default sort is 2, which is further from the chart area than the Legend component's default sort of 1.

title

LegendTitleCfg optional

Legend title configuration. LegendTitleCfg configuration is as follows:

PropertyDescriptionTypeDefault ValueRequired
titleTurn off title or set title contentfalse | stringtrue for continuous legend, false for categorical legend
titleSpacingSpacing from title to content areanumber | number[]4
titleInsetTitle text paddingnumber | number[]0
titlePositionTitle position. Can use abbreviations, e.g., i for inner, lt for left-toptop | bottom |left |right |left-top |left-bottom |right-top |right-bottom |inner-
titleFontSizeTitle text sizenumber | (datum, index, data) => number12
titleFontFamilyTitle text fontstring | (datum, index, data) => string-
titleFontWeightTitle font weightnumber | (datum, index, data) => numbernormal
titleLineHeightTitle text line heightnumber | (datum, index, data) => number-
titleTextAlignSet title text content alignmentcenter | end | left | right | startstart
titleTextBaselineSet text baseline used when drawing title texttop | middle | bottom | alphabetic | hangingbottom
titleFillTitle font colorstring | (datum, index, data) => string#1D2129
titleFillOpacityTitle font color opacitynumber | (datum, index, data) => number0.65
titleStrokeTitle font stroke colorstring | (datum, index, data) => string-
titleStrokeOpacityTitle font stroke color opacitynumber | (datum, index, data) => number-
titleLineWidthTitle font stroke widthnumber | (datum, index, data) => number-
titleLineDashTitle font stroke dash configuration. First value is dash length, second is gap distance. [0,0] means no stroke.[number,number] | (datum, index, data) => [number , number]-
titleOpacityTitle text overall opacitynumber | (datum, index, data) => number-
titleShadowColorTitle text shadow colorstring | (datum, index, data) => string-
titleShadowBlurTitle text shadow Gaussian blur coefficientnumber | (datum, index, data) => number-
titleShadowOffsetXSet horizontal distance from shadow to title textnumber | (datum, index, data) => number-
titleShadowOffsetYSet vertical distance from shadow to title textnumber | (datum, index, data) => number-
titleCursorTitle mouse style. Same as CSS mouse stylesstring | (datum, index, data) => stringdefault

When configuring title in the Legend component, it's not configured as an object, but with title prefix plus property.

({
legend: {
size: {
title: 'Legend Title',
titleSpacing: 0,
titleInset: 0,
titlePosition: 't',
titleFontSize: 16,
titleFontFamily: 'sans-serif',
titleFontWeight: 500,
titleLineHeight: 20,
titleTextAlign: 'center',
titleTextBaseline: 'middle',
titleFill: '#000',
titleFillOpacity: 0.9,
titleStroke: '#DAF5EC',
titleStrokeOpacity: 0.9,
titleLineWidth: 2,
titleLineDash: [4, 8],
titleOpacity: 1,
titleShadowColor: '#d3d3d3',
titleShadowBlur: 10,
titleShadowOffsetX: 10,
titleShadowOffsetY: 10,
titleCursor: 'pointer',
},
},
});

Try it out:

cols

number optional

Applicable to Categorical Legend. Specify the number of legend items displayed per row; empty means no limit on columns.

Legend layout uses flow layout by default.

flow layout

When cols is specified, grid layout is used.

grid layout 1grid layout 2

colPadding

number optional

Applicable to Categorical Legend. Specify horizontal spacing between legend items. Default is 12.

rowPadding

number optional

Applicable to Categorical Legend. Specify vertical spacing between legend items. Default is 8.

maxRows

number optional

Applicable to Categorical Legend. Specify maximum number of rows for legend. Default is 3.

maxCols

number optional

Applicable to Categorical Legend. Specify maximum number of columns for legend. Default is 3.

💡 How do maxRows and maxCols affect legend layout?

maxRows and maxCols are used to limit the maximum number of rows and columns in legend layout. In the code, this is implemented through getRows = (rows) => Math.min(rows, maxRows) and getCols = (cols) => Math.min(cols, maxCols).

ParameterVertical LayoutHorizontal Layout
maxColsLimits columns, controls legend widthNo direct effect (columns specified by cols parameter)
maxRowsNo direct effect (rows calculated by height)Limits rows, controls legend height

Potential Issues

  • Vertical Layout: If maxCols is too small, it may cause single column rows to exceed maxHeight, causing overflow.

  • Horizontal Layout: If maxRows is too small, some items may be truncated.

In this case, you need to appropriately adjust the chart's margin and padding to ensure the legend has enough space to display.

itemMarker

LegendItemMarkerCfg optional

Applicable to Categorical Legend. Configure legend item marker. LegendItemMarkerCfg configuration is as follows:

PropertyDescriptionTypeDefault ValueRequired
itemMarkerLegend item markerSymbols |(datum, index, data)=>Symbolscircle
itemMarkerSizeLegend item marker sizenumber | (datum, index, data) => number8
itemMarkerFillLegend item marker fill colorstring | (datum, index, data) => string-
itemMarkerFillOpacityLegend item marker fill opacitynumber | (datum, index, data) => number1
itemMarkerStrokeLegend item marker strokestring | (datum, index, data) => string-
itemMarkerStrokeOpacityLegend item marker stroke opacitynumber | (datum, index, data) => number-
itemMarkerLineWidthLegend item marker stroke widthnumber | (datum, index, data) => number4 for line-based shapes
itemMarkerLineDashLegend item marker stroke dash configuration. First value is dash length, second is gap distance. [0,0] means no stroke.[number,number] | (datum, index, data) => [number , number]-
itemMarkerOpacityLegend item marker overall opacitynumber | (datum, index, data) => number-
itemMarkerShadowColorLegend item marker shadow colorstring | (datum, index, data) => string-
itemMarkerShadowBlurLegend item marker shadow Gaussian blur coefficientnumber | (datum, index, data) => number-
itemMarkerShadowOffsetXSet horizontal distance from shadow to legend item markernumber | (datum, index, data) => number-
itemMarkerShadowOffsetYSet vertical distance from shadow to legend item markernumber | (datum, index, data) => number-
itemMarkerCursorLegend item marker mouse style. Same as CSS mouse styles.string | (datum, index, data) => stringdefault

Available Symbols Types

PropertyDescription
bowtieShape type: bowtie
crossShape type: cross
dashShape type: dash
diamondShape type: diamond
dotShape type: dot
hexagonShape type: hexagon
hollowBowtieShape type: hollow bowtie
hollowDiamondShape type: hollow diamond
hollowHexagonShape type: hollow hexagon
hollowPointShape type: hollow point
hollowSquareShape type: hollow square
hollowTriangleShape type: hollow triangle
hollowTriangleDownShape type: inverted hollow triangle
hvStyle type: HV path
hvhStyle type: HVH path
hyphenShape type: hyphen
lineShape type: line
plusShape type: plus
pointShape type: solid point
rectShape type: rectangle
smoothStyle type: smooth curve
squareShape type: square
tickShape type: tick
triangleDownShape type: inverted triangle
triangleShape type: triangle
vhStyle type: VH path
vhvStyle type: VHV path

Try it out:

(() => {
// Available itemMarker shapes
const shapeList = [
'bowtie',
'cross',
'dash',
'diamond',
'dot',
'hexagon',
'hollowBowtie',
'hollowDiamond',
'hollowHexagon',
'hollowPoint',
'hollowSquare',
'hollowTriangle',
'hollowTriangleDown',
'hv',
'hvh',
'hyphen',
'line',
'plus',
'point',
'rect',
'smooth',
'square',
'tick',
'triangleDown',
'triangle',
'vh',
'vhv',
];
const shapeMap = shapeList.map((p) => {
return {
label: p,
value: p,
};
});
const chart = new G2.Chart();
chart.options({
type: 'legends',
height: 60,
itemMarker: 'bowtie',
scale: {
color: {
type: 'ordinal',
domain: ['a', 'b'],
range: ['steelblue', 'orange'],
},
},
});
const handleSetShape = (shape) => {
chart.options({
itemMarker: shape,
});
chart.render(); // Re-render the chart
};
const selectorContainer = document.createElement('div');
selectorContainer.textContent = 'Select legend item marker shape ';
const selector = document.createElement('select');
selector.innerHTML = shapeMap.map(
(shape, index) =>
`<option value="${shape.value}" ${index === 0 ? 'selected' : ''}>${
shape.label
}</option>`,
);
selector.onchange = (e) => {
handleSetShape(e.target.value);
};
selectorContainer.appendChild(selector);
const node = chart.getContainer();
node.insertBefore(selectorContainer, node.childNodes[0]);
chart.render();
return node;
})();

When configuring legend item markers in the Legend component, it's not configured as an object, but with itemMarker prefix plus property.

({
legend: {
color: {
itemMarker: 'rect',
itemMarkerSize: 20,
itemMarkerFill: '#000',
itemMarkerFillOpacity: 0.9,
itemMarkerStroke: '#DAF5EC',
itemMarkerStrokeOpacity: 0.9,
itemMarkerLineWidth: 2,
itemMarkerLineDash: [4, 8],
itemMarkerOpacity: 1,
itemMarkerShadowColor: '#d3d3d3',
itemMarkerShadowBlur: 10,
itemMarkerShadowOffsetX: 10,
itemMarkerShadowOffsetY: 10,
itemMarkerCursor: 'pointer',
},
},
});

itemLabel

LegendItemLabelCfg optional

Applicable to Categorical Legend. Configure legend item label. LegendItemLabelCfg configuration is as follows:

PropertyDescriptionTypeDefault ValueRequired
itemLabelTextLegend item label contentstring | (datum, index, data) => string-
itemLabelFontSizeLegend item label text sizenumber | (datum, index, data) => number12
itemLabelFontFamilyLegend item label text fontstring | (datum, index, data) => string-
itemLabelFontWeightLegend item label font weightnumber | (datum, index, data) => numbernormal
itemLabelLineHeightLegend item label text line heightnumber | (datum, index, data) => number-
itemLabelTextAlignSet legend item label text content alignmentcenter | end | left | right | startstart
itemLabelTextBaselineSet text baseline used when drawing legend item label texttop | middle | bottom | alphabetic | hangingbottom
itemLabelFillLegend item label font colorstring | (datum, index, data) => string#1D2129
itemLabelFillOpacityLegend item label font color opacitynumber | (datum, index, data) => number0.9
itemLabelStrokeLegend item label font stroke colorstring | (datum, index, data) => string-
itemLabelStrokeOpacityLegend item label font stroke color opacitynumber | (datum, index, data) => number-
itemLabelLineWidthLegend item label font stroke widthnumber | (datum, index, data) => number-
itemLabelLineDashLegend item label font stroke dash configuration. First value is dash length, second is gap distance. [0,0] means no stroke.[number,number] | (datum, index, data) => [number , number]-
itemLabelOpacityLegend item label text overall opacitynumber | (datum, index, data) => number-
itemLabelShadowColorLegend item label text shadow colorstring | (datum, index, data) => string-
itemLabelShadowBlurLegend item label text shadow Gaussian blur coefficientnumber | (datum, index, data) => number-
itemLabelShadowOffsetXSet horizontal distance from shadow to legend item label textnumber | (datum, index, data) => number-
itemLabelShadowOffsetYSet vertical distance from shadow to legend item label textnumber | (datum, index, data) => number-
itemLabelCursorLegend item label mouse style. Same as CSS mouse stylesstring | (datum, index, data) => stringdefault

When configuring legend item labels in the Legend component, it's not configured as an object, but with itemLabel prefix plus property.

({
legend: {
color: {
itemLabelText: 'Legend Item Label',
itemLabelFontSize: 16,
itemLabelFontFamily: 'sans-serif',
itemLabelFontWeight: 500,
itemLabelLineHeight: 20,
itemLabelTextAlign: 'center',
itemLabelTextBaseline: 'middle',
itemLabelFill: '#000',
itemLabelFillOpacity: 0.9,
itemLabelStroke: '#DAF5EC',
itemLabelStrokeOpacity: 0.9,
itemLabelLineWidth: 2,
itemLabelLineDash: [4, 8],
itemLabelOpacity: 1,
itemLabelShadowColor: '#d3d3d3',
itemLabelShadowBlur: 10,
itemLabelShadowOffsetX: 10,
itemLabelShadowOffsetY: 10,
itemLabelCursor: 'pointer',
},
},
});

itemValue

LegendItemValueCfg optional

Applicable to Categorical Legend. Configure legend item value. LegendItemValueCfg configuration is as follows:

PropertyDescriptionTypeDefault ValueRequired
itemValueTextLegend item value contentstring | (datum, index, data) => string-
itemValueFontSizeLegend item value text sizenumber | (datum, index, data) => number12
itemValueFontFamilyLegend item value text fontstring | (datum, index, data) => string-
itemValueFontWeightLegend item value font weightnumber | (datum, index, data) => numbernormal
itemValueLineHeightLegend item value text line heightnumber | (datum, index, data) => number-
itemValueTextAlignSet legend item value text content alignmentcenter | end | left | right | startstart
itemValueTextBaselineSet text baseline used when drawing legend item value texttop | middle | bottom | alphabetic | hangingbottom
itemValueFillLegend item value font colorstring | (datum, index, data) => string#1D2129
itemValueFillOpacityLegend item value font color opacitynumber | (datum, index, data) => number0.65
itemValueStrokeLegend item value font stroke colorstring | (datum, index, data) => string-
itemValueStrokeOpacityLegend item value font stroke color opacitynumber | (datum, index, data) => number-
itemValueLineWidthLegend item value font stroke widthnumber | (datum, index, data) => number-
itemValueLineDashLegend item value font stroke dash configuration. First value is dash length, second is gap distance. [0,0] means no stroke.[number,number] | (datum, index, data) => [number , number]-
itemValueOpacityLegend item value text overall opacitynumber | (datum, index, data) => number-
itemValueShadowColorLegend item value text shadow colorstring | (datum, index, data) => string-
itemValueShadowBlurLegend item value text shadow Gaussian blur coefficientnumber | (datum, index, data) => number-
itemValueShadowOffsetXSet horizontal distance from shadow to legend item value textnumber | (datum, index, data) => number-
itemValueShadowOffsetYSet vertical distance from shadow to legend item value textnumber | (datum, index, data) => number-
itemValueCursorLegend item value mouse style. Same as CSS mouse stylesstring | (datum, index, data) => stringdefault

When configuring legend item values in the Legend component, it's not configured as an object, but with itemValue prefix plus property.

({
legend: {
color: {
itemValueText: 'Legend Item Value',
itemValueFontSize: 16,
itemValueFontFamily: 'sans-serif',
itemValueFontWeight: 500,
itemValueLineHeight: 20,
itemValueTextAlign: 'center',
itemValueTextBaseline: 'middle',
itemValueFill: '#000',
itemValueFillOpacity: 0.9,
itemValueStroke: '#DAF5EC',
itemValueStrokeOpacity: 0.9,
itemValueLineWidth: 2,
itemValueLineDash: [4, 8],
itemValueOpacity: 1,
itemValueShadowColor: '#d3d3d3',
itemValueShadowBlur: 10,
itemValueShadowOffsetX: 10,
itemValueShadowOffsetY: 10,
itemValueCursor: 'pointer',
},
},
});

itemBackground

LegendItemBackgroundCfg optional

Applicable to Categorical Legend. Configure legend item background. LegendItemBackgroundCfg configuration is as follows:

PropertyDescriptionTypeDefault ValueRequired
itemBackgroundRadiusLegend item background border radiusnumber | (datum, index, data) => number0
itemBackgroundFillLegend item background fill colorstring | (datum, index, data) => stringtransparent
itemBackgroundFillOpacityLegend item background fill opacitynumber | (datum, index, data) => number-
itemBackgroundStrokeLegend item background strokestring | (datum, index, data) => string-
itemBackgroundStrokeOpacityLegend item background stroke opacitynumber | (datum, index, data) => number-
itemBackgroundLineWidthLegend item background stroke widthnumber | (datum, index, data) => number-
itemBackgroundLineDashLegend item background stroke dash configuration. First value is dash length, second is gap distance. [0,0] means no stroke.[number,number] | (datum, index, data) => [number , number]-
itemBackgroundOpacityLegend item background overall opacitynumber | (datum, index, data) => number-
itemBackgroundShadowColorLegend item background shadow colorstring | (datum, index, data) => string-
itemBackgroundShadowBlurLegend item background shadow Gaussian blur coefficientnumber | (datum, index, data) => number-
itemBackgroundShadowOffsetXSet horizontal distance from shadow to legend item backgroundnumber | (datum, index, data) => number-
itemBackgroundShadowOffsetYSet vertical distance from shadow to legend item backgroundnumber | (datum, index, data) => number-
itemBackgroundCursorLegend item background mouse style. Same as CSS mouse styles.string | (datum, index, data) => stringdefault

When configuring legend item background in the Legend component, it's not configured as an object, but with itemBackground prefix plus property.

({
legend: {
color: {
itemBackgroundRadius: 50,
itemBackgroundFill: '#000',
itemBackgroundFillOpacity: 0.9,
itemBackgroundStroke: '#DAF5EC',
itemBackgroundStrokeOpacity: 0.9,
itemBackgroundLineWidth: 2,
itemBackgroundLineDash: [4, 8],
itemBackgroundOpacity: 1,
itemBackgroundShadowColor: '#d3d3d3',
itemBackgroundShadowBlur: 10,
itemBackgroundShadowOffsetX: 10,
itemBackgroundShadowOffsetY: 10,
itemBackgroundCursor: 'pointer',
},
},
});

Next, let's try combining various properties of itemMarker, itemLabel, itemValue, and itemBackground to configure a custom legend:

itemWidth

number optional

Applicable to Categorical Legend. Configure legend item width.

itemSpan

number|number[] optional

Applicable to Categorical Legend. Configure space allocation for legend item marker, label, and value. Default is [1, 1, 1].

itemSpacing

number|number[] optional

Applicable to Categorical Legend. Configure spacing between legend item marker, label, and value. Default is [8, 8].

nav

LegendNavCfg optional

Applicable to Categorical Legend. Configure legend navigator. In grid layout, page capacity = gridRow × gridCol. If the number of categorical items exceeds this capacity, pagination occurs. In flex layout, page capacity is dynamically calculated and limited by container width and height. When categorical items exceed container height or width, pagination occurs and the navigator component is displayed. LegendNavCfg configuration is as follows:

legend-nav
PropertyDescriptionTypeDefault ValueRequired
navEffectPage transition effectSee Web Animations APIlinear
navDurationSingle page transition animation durationnumber200
navOrientationPage scroll direction
- Horizontal horizontal
- Vertical vertical
horizontal |verticalhorizontal
navDefaultPageDefault page number to displaynumber0
navLoopWhether to enable loop paginationbooleanfalse
navPageWidthNavigator page widthnumber-
navPageHeightNavigator page heightnumber-
navControllerPaddingSpacing between navigator buttons and page numbersnumber | number[]5
navControllerSpacingSpacing between navigator buttons and page, can be used to configure spacing between navigator and legendnumber | number[]5
navPageNumFontSizeNavigator page number text sizenumber | (datum, index, data) => number12
navPageNumFontFamilyNavigator page number text fontstring | (datum, index, data) => string-
navPageNumFontWeightNavigator page number font weightnumber | (datum, index, data) => numbernormal
navPageNumLineHeightNavigator page number text line heightnumber | (datum, index, data) => number-
navPageNumTextAlignSet navigator page number text content alignmentcenter | end | left | right | startstart
navPageNumTextBaselineSet text baseline used when drawing navigator page number texttop | middle | bottom | alphabetic | hangingbottom
navPageNumFillNavigator page number font colorstring | (datum, index, data) => string#1D2129
navPageNumFillOpacityNavigator page number font color opacitynumber | (datum, index, data) => number0.45
navPageNumStrokeNavigator page number font stroke colorstring | (datum, index, data) => string-
navPageNumStrokeOpacityNavigator page number font stroke color opacitynumber | (datum, index, data) => number-
navPageNumLineWidthNavigator page number font stroke widthnumber | (datum, index, data) => number-
navPageNumLineDashNavigator page number font stroke dash configuration. First value is dash length, second is gap distance. [0,0] means no stroke.[number,number] | (datum, index, data) => [number , number]-
navPageNumOpacityNavigator page number text overall opacitynumber | (datum, index, data) => number-
navPageNumShadowColorNavigator page number text shadow colorstring | (datum, index, data) => string-
navPageNumShadowBlurNavigator page number text shadow Gaussian blur coefficientnumber | (datum, index, data) => number-
navPageNumShadowOffsetXSet horizontal distance from shadow to navigator page number textnumber | (datum, index, data) => number-
navPageNumShadowOffsetYSet vertical distance from shadow to navigator page number textnumber | (datum, index, data) => number-
navPageNumCursorNavigator page number mouse style. Same as CSS mouse stylesstring | (datum, index, data) => stringdefault
navButtonSizeNavigator button sizenumber | (datum, index, data) => number-
navButtonFillNavigator button fill colorstring | (datum, index, data) => string#1D2129
navButtonFillOpacityNavigator button fill opacitynumber | (datum, index, data) => number0.65
navButtonStrokeNavigator button strokestring | (datum, index, data) => string-
navButtonStrokeOpacityNavigator button stroke opacitynumber | (datum, index, data) => number-
navButtonLineWidthNavigator button stroke widthnumber | (datum, index, data) => number-
navButtonLineDashNavigator button stroke dash configuration. First value is dash length, second is gap distance. [0,0] means no stroke.[number,number] | (datum, index, data) => [number , number]-
navButtonOpacityNavigator button overall opacitynumber | (datum, index, data) => number-
navButtonShadowColorNavigator button shadow colorstring | (datum, index, data) => string-
navButtonShadowBlurNavigator button shadow Gaussian blur coefficientnumber | (datum, index, data) => number-
navButtonShadowOffsetXSet horizontal distance from shadow to navigator buttonnumber | (datum, index, data) => number-
navButtonShadowOffsetYSet vertical distance from shadow to navigator buttonnumber | (datum, index, data) => number-
navButtonCursorNavigator button mouse style. Same as CSS mouse styles.string | (datum, index, data) => stringdefault
navFormatterPage number text formatter(current: number, total: number) => string-

When configuring navigator properties in the Legend component, it's not configured as an object, but with nav prefix plus property.

({
legend: {
color: {
navEffect: 'cubic-bezier',
navDuration: 400,
navOrientation: 'vertical',
navDefaultPage: 1,
navLoop: true,
navPageWidth: 10,
navPageHeight: 10,
navControllerPadding: 10,
navControllerSpacing: 10,
// Configure navPageNum drawing properties
navPageNumFontSize: 16,
navPageNumFontFamily: 'sans-serif',
navPageNumFontWeight: 500,
navPageNumLineHeight: 20,
navPageNumTextAlign: 'center',
navPageNumTextBaseline: 'middle',
navPageNumFill: '#000',
navPageNumFillOpacity: 0.9,
navPageNumStroke: '#DAF5EC',
navPageNumStrokeOpacity: 0.9,
navPageNumLineWidth: 2,
navPageNumLineDash: [4, 8],
navPageNumOpacity: 1,
navPageNumShadowColor: '#d3d3d3',
navPageNumShadowBlur: 10,
navPageNumShadowOffsetX: 10,
navPageNumShadowOffsetY: 10,
navPageNumCursor: 'pointer',
// Configure navButton drawing properties
navButtonFill: '#000',
navButtonFillOpacity: 0.9,
navButtonStroke: '#DAF5EC',
navButtonStrokeOpacity: 0.9,
navButtonLineWidth: 2,
navButtonLineDash: [4, 8],
navButtonOpacity: 1,
navButtonShadowColor: '#d3d3d3',
navButtonShadowBlur: 10,
navButtonShadowOffsetX: 10,
navButtonShadowOffsetY: 10,
navButtonCursor: 'pointer',
},
},
});

Try it out:

color

string[] | d3-interpolate optional

Applicable to Continuous Legend. Configure color band colors for continuous legend. When it's an array, colors are taken in order.

block

boolean optional

Applicable to Continuous Legend. Whether continuous legend displays by intervals. Default is false.

type

size | color optional

Applicable to Continuous Legend. Configure type of continuous legend. Default is color.

Combining block and type properties allows you to configure different styles of continuous legends. Continuous data legends have 4 styles:

  • Continuous representation default

    ribbon-color
  • Range representation block=true

    ribbon-color
  • Size representation type='size'

    ribbon-color
  • Size, range representation type='size' block=true

    ribbon-color

ribbon

LegendRibbonCfg optional

Applicable to Continuous Legend. Configure color band of continuous legend. LegendRibbonCfg configuration is as follows:

PropertyDescriptionTypeDefault ValueRequired
ribbonSizeColor band sizenumber | (datum, index, data) => number12
ribbonFillColor band fill colorstring | (datum, index, data) => string#aaa
ribbonFillOpacityColor band fill opacitynumber | (datum, index, data) => number-
ribbonStrokeColor band strokestring | (datum, index, data) => string-
ribbonStrokeOpacityColor band stroke opacitynumber | (datum, index, data) => number-
ribbonLineWidthColor band stroke widthnumber | (datum, index, data) => number-
ribbonLineDashColor band stroke dash configuration. First value is dash length, second is gap distance. [0,0] means no stroke.[number,number] | (datum, index, data) => [number , number]-
ribbonOpacityColor band overall opacitynumber | (datum, index, data) => number-
ribbonShadowColorColor band shadow colorstring | (datum, index, data) => string-
ribbonShadowBlurColor band shadow Gaussian blur coefficientnumber | (datum, index, data) => number-
ribbonShadowOffsetXSet horizontal distance from shadow to color bandnumber | (datum, index, data) => number-
ribbonShadowOffsetYSet vertical distance from shadow to color bandnumber | (datum, index, data) => number-
ribbonCursorColor band mouse style. Same as CSS mouse styles.string | (datum, index, data) => stringdefault

When configuring color band in the Legend component, it's not configured as an object, but with ribbon prefix plus property.

({
legend: {
color: {
ribbonSize: 20,
ribbonFill: '#000',
ribbonFillOpacity: 0.9,
ribbonStroke: '#DAF5EC',
ribbonStrokeOpacity: 0.9,
ribbonLineWidth: 2,
ribbonLineDash: [4, 8],
ribbonOpacity: 1,
ribbonShadowColor: '#d3d3d3',
ribbonShadowBlur: 10,
ribbonShadowOffsetX: 10,
ribbonShadowOffsetY: 10,
ribbonCursor: 'pointer',
},
},
});

handle

LegendHandleCfg optional

The slider window marks the current value selection range. Through interaction with the slider window, you can select the value range in the view.

slider-window

Applicable to Continuous Legend. Configure slider handle of continuous legend. LegendHandleCfg configuration is as follows:

PropertyDescriptionTypeDefault ValueRequired
handleWhether to display slider handlebooleantrue
handleLabelWhether to display slider handle labelsbooleanfalse
slidableWhether window is slidablebooleantrue
rangeDefault selection range for slider window[number, number][min, max]
stepSingle slide step sizenumber1
handleLabelFontSizeHandle label text sizenumber | (datum, index, data) => number12
handleLabelFontFamilyHandle label text fontstring | (datum, index, data) => string-
handleLabelFontWeightHandle label font weightnumber | (datum, index, data) => numbernormal
handleLabelLineHeightHandle label text line heightnumber | (datum, index, data) => number-
handleLabelTextAlignSet handle label text content alignmentcenter | end | left | right | startstart
handleLabelTextBaselineSet text baseline used when drawing handle label texttop | middle | bottom | alphabetic | hangingbottom
handleLabelFillHandle label font colorstring | (datum, index, data) => string#1D2129
handleLabelFillOpacityHandle label font color opacitynumber | (datum, index, data) => number0.45
handleLabelStrokeHandle label font stroke colorstring | (datum, index, data) => string-
handleLabelStrokeOpacityHandle label font stroke color opacitynumber | (datum, index, data) => number-
handleLabelLineWidthHandle label font stroke widthnumber | (datum, index, data) => number-
handleLabelLineDashHandle label font stroke dash configuration. First value is dash length, second is gap distance. [0,0] means no stroke.[number,number] | (datum, index, data) => [number , number]-
handleLabelOpacityHandle label text overall opacitynumber | (datum, index, data) => number-
handleLabelShadowColorHandle label text shadow colorstring | (datum, index, data) => string-
handleLabelShadowBlurHandle label text shadow Gaussian blur coefficientnumber | (datum, index, data) => number-
handleLabelShadowOffsetXSet horizontal distance from shadow to handle label textnumber | (datum, index, data) => number-
handleLabelShadowOffsetYSet vertical distance from shadow to handle label textnumber | (datum, index, data) => number-
handleLabelCursorHandle label mouse style. Same as CSS mouse stylesstring | (datum, index, data) => stringdefault
handleIconSizeHandle icon sizenumber | (datum, index, data) => number-
handleIconFillHandle icon fill colorstring | (datum, index, data) => string#1D2129
handleIconFillOpacityHandle icon fill opacitynumber | (datum, index, data) => number0.65
handleIconStrokeHandle icon strokestring | (datum, index, data) => string-
handleIconStrokeOpacityHandle icon stroke opacitynumber | (datum, index, data) => number-
handleIconLineWidthHandle icon stroke widthnumber | (datum, index, data) => number-
handleIconLineDashHandle icon stroke dash configuration. First value is dash length, second is gap distance. [0,0] means no stroke.[number,number] | (datum, index, data) => [number , number]-
handleIconOpacityHandle icon overall opacitynumber | (datum, index, data) => number-
handleIconShadowColorHandle icon shadow colorstring | (datum, index, data) => string-
handleIconShadowBlurHandle icon shadow Gaussian blur coefficientnumber | (datum, index, data) => number-
handleIconShadowOffsetXSet horizontal distance from shadow to handle iconnumber | (datum, index, data) => number-
handleIconShadowOffsetYSet vertical distance from shadow to handle iconnumber | (datum, index, data) => number-
handleIconCursorHandle icon mouse style. Same as CSS mouse styles.string | (datum, index, data) => stringdefault

When configuring continuous legend slider handle properties in the Legend component, it's not configured as an object, but with handle prefix plus property.

({
legend: {
color: {
handle: true,
handleLabel: true,
slidable: true,
range: [0, 1],
step: 1,
// Configure handleLabel drawing properties
handleLabelFontSize: 16,
handleLabelFontFamily: 'sans-serif',
handleLabelFontWeight: 500,
handleLabelLineHeight: 20,
handleLabelTextAlign: 'center',
handleLabelTextBaseline: 'middle',
handleLabelFill: '#000',
handleLabelFillOpacity: 0.9,
handleLabelStroke: '#DAF5EC',
handleLabelStrokeOpacity: 0.9,
handleLabelLineWidth: 2,
handleLabelLineDash: [4, 8],
handleLabelOpacity: 1,
handleLabelShadowColor: '#d3d3d3',
handleLabelShadowBlur: 10,
handleLabelShadowOffsetX: 10,
handleLabelShadowOffsetY: 10,
handleLabelCursor: 'pointer',
handleIconSize: 50,
// Configure handleIcon drawing properties
handleIconFill: '#000',
handleIconFillOpacity: 0.9,
handleIconStroke: '#DAF5EC',
handleIconStrokeOpacity: 0.9,
handleIconLineWidth: 2,
handleIconLineDash: [4, 8],
handleIconOpacity: 1,
handleIconShadowColor: '#d3d3d3',
handleIconShadowBlur: 10,
handleIconShadowOffsetX: 10,
handleIconShadowOffsetY: 10,
handleIconCursor: 'pointer',
},
},
});

label

LegendLabelCfg optional

Applicable to Continuous Legend. Configure labels/tick values of continuous legend. LegendLabelCfg configuration is as follows:

PropertyDescriptionTypeDefault ValueRequired
labelWhether to display continuous legend tick valuesbooleantrue
labelFormatterContinuous legend tick value formatter(datum, index, data)=>string-
labelFilterContinuous legend tick value filter(datum, index, data)=>boolean-
labelDirectionPosition of continuous legend tick values relative to color band, refer to axis directionpositive | negativepositive
labelSpacingSpacing from continuous legend tick values to color bandnumber3
labelAlignContinuous legend tick value alignment
- 'value' align to tick
- 'range' align to range
value | rangevalue
labelFontSizeContinuous legend tick value text sizenumber | (datum, index, data) => number12
labelFontFamilyContinuous legend tick value text fontstring | (datum, index, data) => string-
labelFontWeightContinuous legend tick value font weightnumber | (datum, index, data) => numbernormal
labelLineHeightContinuous legend tick value text line heightnumber | (datum, index, data) => number-
labelTextAlignSet continuous legend tick value text content alignmentcenter | end | left | right | startstart
labelTextBaselineSet text baseline used when drawing continuous legend tick value texttop | middle | bottom | alphabetic | hangingbottom
labelFillContinuous legend tick value font colorstring | (datum, index, data) => string#1D2129
labelFillOpacityContinuous legend tick value font color opacitynumber | (datum, index, data) => number0.45
labelStrokeContinuous legend tick value font stroke colorstring | (datum, index, data) => string-
labelStrokeOpacityContinuous legend tick value font stroke color opacitynumber | (datum, index, data) => number-
labelLineWidthContinuous legend tick value font stroke widthnumber | (datum, index, data) => number-
labelLineDashContinuous legend tick value font stroke dash configuration. First value is dash length, second is gap distance. [0,0] means no stroke.[number,number] | (datum, index, data) => [number , number]-
labelOpacityContinuous legend tick value text overall opacitynumber | (datum, index, data) => number-
labelShadowColorContinuous legend tick value text shadow colorstring | (datum, index, data) => string-
labelShadowBlurContinuous legend tick value text shadow Gaussian blur coefficientnumber | (datum, index, data) => number-
labelShadowOffsetXSet horizontal distance from shadow to continuous legend tick value textnumber | (datum, index, data) => number-
labelShadowOffsetYSet vertical distance from shadow to continuous legend tick value textnumber | (datum, index, data) => number-
labelCursorHandle label mouse style. Same as CSS mouse stylesstring | (datum, index, data) => stringdefault

Tick value alignment methods

  • Align to tick
align-tick
  • Align to range
align-range

When configuring continuous legend labels/tick values properties in the Legend component, it's not configured as an object, but with label prefix plus property.

({
legend: {
color: {
label: true,
labelFormatter: (d) => {},
labelFilter: (datum, index, data) => {},
labelDirection: 'positive',
labelSpacing: 5,
labelAlign: 'range',
// Configure continuous legend tick value label drawing properties
labelFontSize: 16,
labelFontFamily: 'sans-serif',
labelFontWeight: 500,
labelLineHeight: 20,
labelTextAlign: 'center',
labelTextBaseline: 'middle',
labelFill: '#000',
labelFillOpacity: 0.9,
labelStroke: '#DAF5EC',
labelStrokeOpacity: 0.9,
labelLineWidth: 2,
labelLineDash: [4, 8],
labelOpacity: 1,
labelShadowColor: '#d3d3d3',
labelShadowBlur: 10,
labelShadowOffsetX: 10,
labelShadowOffsetY: 10,
labelCursor: 'pointer',
},
},
});

indicator

LegendIndicatorCfg optional

Applicable to Continuous Legend. Configure indicator of continuous legend. The indicator is a tooltip component that indicates the value at the current position during interaction with the continuous legend.

indicator

LegendIndicatorCfg configuration is as follows:

PropertyDescriptionTypeDefault ValueRequired
indicatorWhether to display continuous legend value indicatorbooleanfalse
indicatorFormatterValue indicator formatter(datum, index, data)=>string-
indicatorLabelFontSizeValue indicator text sizenumber | (datum, index, data) => number-
indicatorLabelFontFamilyValue indicator text fontstring | (datum, index, data) => string-
indicatorLabelFontWeightValue indicator font weightnumber | (datum, index, data) => number-
indicatorLabelLineHeightValue indicator text line heightnumber | (datum, index, data) => number-
indicatorLabelTextAlignSet value indicator text content alignmentcenter | end | left | right | startstart
indicatorLabelTextBaselineSet text baseline used when drawing value indicator texttop | middle | bottom | alphabetic | hangingbottom
indicatorLabelFillValue indicator font colorstring | (datum, index, data) => string-
indicatorLabelFillOpacityValue indicator font color opacitynumber | (datum, index, data) => number-
indicatorLabelStrokeValue indicator font stroke colorstring | (datum, index, data) => string-
indicatorLabelStrokeOpacityValue indicator font stroke color opacitynumber | (datum, index, data) => number-
indicatorLabelLineWidthValue indicator font stroke widthnumber | (datum, index, data) => number-
indicatorLabelLineDashValue indicator font stroke dash configuration. First value is dash length, second is gap distance. [0,0] means no stroke.[number,number] | (datum, index, data) => [number , number]-
indicatorLabelOpacityValue indicator text overall opacitynumber | (datum, index, data) => number-
indicatorLabelShadowColorValue indicator text shadow colorstring | (datum, index, data) => string-
indicatorLabelShadowBlurValue indicator text shadow Gaussian blur coefficientnumber | (datum, index, data) => number-
indicatorLabelShadowOffsetXSet horizontal distance from shadow to value indicator textnumber | (datum, index, data) => number-
indicatorLabelShadowOffsetYSet vertical distance from shadow to value indicator textnumber | (datum, index, data) => number-
indicatorLabelCursorValue indicator mouse style. Same as CSS mouse stylesstring | (datum, index, data) => stringdefault
indicatorBackgroundFillValue indicator background fill colorstring | (datum, index, data) => string-
indicatorBackgroundFillOpacityValue indicator background fill opacitynumber | (datum, index, data) => number-
indicatorBackgroundStrokeValue indicator background strokestring | (datum, index, data) => string-
indicatorBackgroundStrokeOpacityValue indicator background stroke opacitynumber | (datum, index, data) => number-
indicatorBackgroundLineWidthValue indicator background stroke widthnumber | (datum, index, data) => number-
indicatorBackgroundLineDashValue indicator background stroke dash configuration. First value is dash length, second is gap distance. [0,0] means no stroke.[number,number] | (datum, index, data) => [number , number]-
indicatorBackgroundOpacityValue indicator background overall opacitynumber | (datum, index, data) => number-
indicatorBackgroundShadowColorValue indicator background shadow colorstring | (datum, index, data) => string-
indicatorBackgroundShadowBlurValue indicator background shadow Gaussian blur coefficientnumber | (datum, index, data) => number-
indicatorBackgroundShadowOffsetXSet horizontal distance from shadow to value indicator backgroundnumber | (datum, index, data) => number-
indicatorBackgroundShadowOffsetYSet vertical distance from shadow to value indicator backgroundnumber | (datum, index, data) => number-
indicatorBackgroundCursorValue indicator background mouse style. Same as CSS mouse styles.string | (datum, index, data) => stringdefault

When configuring value indicator properties in the Legend component, it's not configured as an object, but with indicator prefix plus property.

({
legend: {
color: {
indicator: 'true',
indicatorFormatter: (d) => {},
// Configure indicatorLabel drawing properties
indicatorLabelFontSize: 16,
indicatorLabelFontFamily: 'sans-serif',
indicatorLabelFontWeight: 500,
indicatorLabelLineHeight: 20,
indicatorLabelTextAlign: 'center',
indicatorLabelTextBaseline: 'middle',
indicatorLabelFill: '#000',
indicatorLabelFillOpacity: 0.9,
indicatorLabelStroke: '#DAF5EC',
indicatorLabelStrokeOpacity: 0.9,
indicatorLabelLineWidth: 2,
indicatorLabelLineDash: [4, 8],
indicatorLabelOpacity: 1,
indicatorLabelShadowColor: '#d3d3d3',
indicatorLabelShadowBlur: 10,
indicatorLabelShadowOffsetX: 10,
indicatorLabelShadowOffsetY: 10,
indicatorLabelCursor: 'pointer',
// Configure indicatorBackground drawing properties
indicatorBackgroundFill: '#000',
indicatorBackgroundFillOpacity: 0.9,
indicatorBackgroundStroke: '#DAF5EC',
indicatorBackgroundStrokeOpacity: 0.9,
indicatorBackgroundLineWidth: 2,
indicatorBackgroundLineDash: [4, 8],
indicatorBackgroundOpacity: 1,
indicatorBackgroundShadowColor: '#d3d3d3',
indicatorBackgroundShadowBlur: 10,
indicatorBackgroundShadowOffsetX: 10,
indicatorBackgroundShadowOffsetY: 10,
indicatorBackgroundCursor: 'pointer',
},
},
});

Events

The Legend component exposes some special events for getting component interaction information.

Event TypeDescriptionType
click Categorical LegendTriggered when clicking legend item(item:Selection)=>void
mouseenter Categorical LegendTriggered when mouse enters legend item(item: Selection)=>void
mouseleave Categorical LegendTriggered when mouse leaves legend item(item:Selection)=>void
valuechange Continuous LegendTriggered when slider window selection range changes(range: [number, number])=>void
indicate Continuous LegendTriggered when indicator value changes(value: number, range: [number, number])=>void

Components appear after chart rendering, so component events should be mounted after afterrender. Here's an example:

chart.on('afterrender', () => {
const { canvas } = chart.getContext();
const { document } = canvas;
document
.querySelector('.component')
.addEventListener('valuechange', (range) => {});
});

Examples

Default Display of Only Partial Legends on First Chart Render

There's currently no built-in API for this, so you need to manually trigger legendFilter to achieve it.

import { Chart, ChartEvent } from '@antv/g2';
const chart = new Chart({ container: 'container' });
chart.options({
type: 'interval',
data: [
{ genre: 'Sports', sold: 100 },
{ genre: 'Strategy', sold: 115 },
{ genre: 'Action', sold: 120 },
{ genre: 'Shooter', sold: 350 },
{ genre: 'Other', sold: 150 },
],
encode: { x: 'genre', y: 'sold', color: 'genre' },
});
chart.render();
chart.on(ChartEvent.AFTER_RENDER, () => {
chart.emit('legend:filter', {
data: { channel: 'color', values: ['Sports', 'Strategy', 'Action'] },
});
});

Custom Legend Item Marker (itemMarker)

In actual development, the built-in legend item markers may not meet your requirements. Don't worry, G2 provides powerful customization features.

Custom Symbol

Each symbol can be customized, mainly in three steps:

  • Define symbol path.
  • Register symbol.
  • Use symbol.

First, let's see how to define a symbol path. A symbol path is a function that takes the starting point coordinates x, y and drawing radius, and returns a path.

import { type SymbolFactor } from '@antv/g2';
const triangle: SymbolFactor = (x, y, r) => {
const diffY = r * Math.sin((1 / 3) * Math.PI);
return [
['M', x - r, y + diffY],
['L', x, y - diffY],
['L', x + r, y + diffY],
['Z'],
];
};
triangle.style = ['fill'];

Next is registering the symbol, by calling G2.register('symbol.${symbol}', Symbol). Where symbol is the symbol name and Symbol is the defined symbol path. For example, registering a triangle symbol:

import { register } from '@antv/g2';
register('symbol.customTriangle', triangle);

Finally, use the symbol:

legend: {
color: {
itemMarker: 'customTriangle';
}
}

Using Images

import { Chart } from '@antv/g2';
const chart = new Chart({
container: 'container',
});
const logo = [
[
'TikTok',
'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*8IXHQLvx9QkAAAAAAAAAAAAADmJ7AQ/original',
],
[
'Kuaishou',
'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*swueRrrKvbcAAAAAAAAAAAAADmJ7AQ/original',
],
[
'Xiaomi',
'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*79G3TIt3mBoAAAAAAAAAAAAADmJ7AQ/original',
],
[
'WeChat',
'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*_ELBTJLp0dQAAAAAAAAAAAAADmJ7AQ/original',
],
[
'Keep',
'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*JzbKRpFhR14AAAAAAAAAAAAADmJ7AQ/original',
],
[
'Chrome',
'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*xLnYTaZfdh8AAAAAAAAAAAAADmJ7AQ/original',
],
[
'QQ',
'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*AbGNTpA5JLwAAAAAAAAAAAAADmJ7AQ/original',
],
[
'Youku',
'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*UL6lS4jw9lUAAAAAAAAAAAAADmJ7AQ/original',
],
[
'Baidu Maps',
'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*I6nrTITAxcoAAAAAAAAAAAAADmJ7AQ/original',
],
[
'Tencent Video',
'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*zwVvT5OFnuYAAAAAAAAAAAAADmJ7AQ/original',
],
[
'Bilibili',
'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*6jkAQayTiMMAAAAAAAAAAAAADmJ7AQ/original',
],
[
'Word',
'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*FbkXT6K6mVEAAAAAAAAAAAAADmJ7AQ/original',
],
[
'Excel',
'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*CKb-R6ZAFpYAAAAAAAAAAAAADmJ7AQ/original',
],
[
'PowerPoint',
'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*K7-FT4RYRqIAAAAAAAAAAAAADmJ7AQ/original',
],
[
'Tencent Meeting',
'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*xbPXR7snu44AAAAAAAAAAAAADmJ7AQ/original',
],
[
'NetEase Cloud Music',
'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*upKlRJ9QB4cAAAAAAAAAAAAADmJ7AQ/original',
],
[
'Safari',
'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*kjDHRbiW734AAAAAAAAAAAAADmJ7AQ/original',
],
[
'Maps',
'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*tl-2QIB8LKIAAAAAAAAAAAAADmJ7AQ/original',
],
[
'Docker',
'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*iJ4dS49yrJ4AAAAAAAAAAAAADmJ7AQ/original',
],
[
'VSCode',
'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*rR6nRInEcz4AAAAAAAAAAAAADmJ7AQ/original',
],
[
'Baidu Netdisk',
'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*futaTbIAkG4AAAAAAAAAAAAADmJ7AQ/original',
],
[
'Evernote',
'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*Skh1S4BfL9oAAAAAAAAAAAAADmJ7AQ/original',
],
];
chart
.interval()
.data(logo)
.encode('x', (d) => d[0])
.encode('y', () => Math.random())
.encode('color', (d) => d[1])
.scale('y', { nice: true })
.legend({
color: {
itemMarker: (_, index) => () => {
const { document } = chart.getContext().canvas;
const image = document.createElement('image', {
style: {
width: 20,
height: 20,
transform: `translate(-10, -10)`,
src: logo[index][1],
},
});
return image;
},
itemMarkerSize: 40,
itemLabelText: (_, index) => logo[index][0],
maxRows: 1,
},
})
.tooltip(false);
chart.render();

Custom Legend

G2's built-in legends are drawn with canvas or svg. If you want to render legends with HTML, you can customize legends by following these steps:

  • Turn off built-in legends and render the chart.
  • Wait for chart rendering to complete, then render HTML legend based on scale data.
  • Add interactions (if needed).

First, turn off built-in legends and render the chart.

chart.options({ legend: false });

Then wait for chart rendering to complete and call legendColor to render HTML legend:

chart.render().then(legendColor);

In legendColor, we first need to draw the legend. The following example draws the legend and adds it in front of the canvas:

function legendColor(chart) {
const node = chart.getContainer();
const legend = document.createElement('div');
node.insertBefore(legend, node.childNodes[0]);
// ...
}

After drawing the legend, we need to draw legend items. This data comes from the corresponding channel's scale: chart.getScale().color, and get corresponding names and values through the scale's domain and range.

function legendColor(chart) {
// ...
const scale = chart.getScale().color;
const { domain } = scale.getOptions();
const items = domain.map(() => {});
// ...
}

After drawing legend items, we should add interactions to each legend item through item.onclick, collect currently selected values, and add Filter transforms to the chart declaration based on these values, then re-render the chart. The complete implementation is as follows:

import { Chart } from '@antv/g2';
// Add legend
function legendColor(chart) {
// Create Legend and mount legend
const node = chart.getContainer();
const legend = document.createElement('div');
legend.style.display = 'flex';
node.insertBefore(legend, node.childNodes[0]);
// Create and mount Items
const { color: scale } = chart.getScale();
const { domain } = scale.getOptions();
const items = domain.map((value) => {
const item = document.createElement('div');
const color = scale.map(value);
item.style.marginLeft = '1em';
item.innerHTML = `
<span style="
background-color:${color};
display:inline-block;
width:10px;
height:10px;"
></span>
<span>${value}</span>
`;
return item;
});
items.forEach((d) => legend.append(d));
// Listen to events
const selectedValues = [...domain];
const options = chart.options();
for (let i = 0; i < items.length; i++) {
const item = items[i];
const value = domain[i];
item.style.cursor = 'pointer';
item.onclick = () => {
const index = selectedValues.indexOf(value);
if (index !== -1) {
selectedValues.splice(index, 1);
item.style.opacity = 0.5;
} else {
selectedValues.push(value);
item.style.opacity = 1;
}
changeColor(selectedValues);
};
}
// Re-render view
function changeColor(value) {
const { transform = [] } = options;
const newTransform = [{ type: 'filter', color: { value } }, ...transform];
chart.options({
...options,
transform: newTransform, // Specify new transform
scale: { color: { domain } },
});
chart.render(); // Re-render chart
}
}
// Draw chart
const container = document.createElement('div');
const chart = new Chart({
container: 'container',
container,
});
chart.options({
type: 'interval',
data: [
{ genre: 'Sports', sold: 275 },
{ genre: 'Strategy', sold: 115 },
{ genre: 'Action', sold: 120 },
{ genre: 'Shooter', sold: 350 },
{ genre: 'Other', sold: 150 },
],
encode: { x: 'genre', y: 'sold', color: 'genre' },
legend: false,
});
chart.render().then(legendColor);