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)

Slider

Previous
Scrollbar
Next
Tooltip

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

The Slider in G2 can be used to filter data, allowing users to focus on local data at a time when dealing with large datasets. It's an auxiliary component for data visualization. It condenses large amounts of data onto an axis, enabling users to view data at both macro and micro levels, and drag to observe data evolution within a certain range. The slider can be bound to x or y channels to display sliders in different directions. Sliders are disabled by default.

import { Chart } from '@antv/g2';
const chart = new Chart({
container: 'container',
});
const formatter = (dateTimeString) => {
return new Date(dateTimeString).toLocaleString();
};
chart.options({
type: 'line',
autoFit: true,
data: {
type: 'fetch',
value:
'https://gw.alipayobjects.com/os/bmw-prod/551d80c6-a6be-4f3c-a82a-abd739e12977.csv',
},
encode: { x: 'date', y: 'close' },
slider: {
x: {
labelFormatter: (d) => `${formatter(d)}`,
},
},
});
chart.render();

Configuration Hierarchy

Sliders can be configured at the Mark level. In G2, each mark has its own slider. If the scales corresponding to marks are synchronized, the sliders will also be merged.

({
type: 'interval',
slider: {
x: {},
y: {},
},
});

Sliders can also be configured at the View level. Sliders have inheritance. Sliders declared on a view will be passed to the marks declared in children. If the mark has a slider for the corresponding channel, they will be merged; otherwise, it won't affect anything.

({
type: 'view',
slider: {
x: {},
y: {},
},
});

When to Use

Sliders are condensed representations of value domain data, closely related to the scale types corresponding to position channels x and y. Generally, sliders are more frequently used with temporal scales, less frequently with continuous scales, and almost never with categorical scales.

slider
  • Temporal axis with very large data span [High frequency use]: For example, when time series data spans 10 years and you need to observe data trends during this period, it's recommended to enable the slider;
  • Temporal axis with high data density [High frequency use]: For example, minute-level real-time data updates. When you need to view data trends within a day, it's recommended to enable the slider;
  • Continuous axis with high data density [Low frequency use]: For example, viewing average height distribution for ages 1-100. Enabling the slider allows global viewing of height distribution;
  • Categorical axis [Not recommended].

Usage

slider
import { Chart } from '@antv/g2';
const chart = new Chart({
container: 'container',
});
chart.options({
type: 'line',
data: {
type: 'fetch',
value:
'https://gw.alipayobjects.com/os/bmw-prod/551d80c6-a6be-4f3c-a82a-abd739e12977.csv',
},
encode: { x: 'date', y: 'close' },
slider: { y: {} }, // Enable Y-direction slider
});
chart.render();

Configuration Options

PropertyDescriptionTypeDefaultRequired
paddingSlider inner paddingnumber | number[]-
valuesInitial selection range of slider, within 0 ~ 1 interval[number, number]-
slidableWhether to allow dragging selection and handlesbooleantrue
brushableWhether to enable brushingbooleantrue
labelFormatterSlider handle label formatter(value: number)=>string-
showHandleWhether to show drag handlesbooleantrue
showLabelWhether to show handle textbooleantrue
showLabelOnInteractionShow handle text only when adjusting handles or brushing, effective when showLabel is falsebooleanfalse
autoFitLabelWhether to automatically adjust handle text positionbooleantrue
styleConfigure slider component stylesstyleSee style

style

Configure slider component styles.

PropertyDescriptionTypeDefaultRequired
selectionConfigure selection area stylesselectionSee selection
trackConfigure track stylestrackSee track
handleConfigure handle styleshandleSee handle
sparklineConfigure sparkline stylessparklineSee sparkline

selection

Configure slider selection area styles.

PropertyDescriptionTypeDefaultRequired
selectionFillSelection area fill colorstring#1783FF
selectionFillOpacitySelection area fill opacitynumber0.15
selectionStrokeSelection area stroke colorstring-
selectionStrokeOpacitySelection area stroke opacitynumber-
selectionLineWidthSelection area stroke widthnumber-
selectionLineDashSelection area stroke dash configuration[number,number]-
selectionOpacitySelection area overall opacitynumber-
selectionShadowColorSelection area shadow colorstring-
selectionShadowBlurSelection area shadow blur coefficientnumber-
selectionShadowOffsetXSelection area shadow horizontal offsetnumber-
selectionShadowOffsetYSelection area shadow vertical offsetnumber-
selectionCursorSelection area cursor stylestringdefault

When configuring selection styles in the Slider component, use the selection prefix with properties instead of object configuration.

({
slider: {
x: {
// Can be configured outside style as well, G2 internally handles compatibility
style: {
selectionFill: '#000',
selectionFillOpacity: 0.9,
selectionStroke: '#DAF5EC',
selectionStrokeOpacity: 0.9,
selectionLineWidth: 2,
selectionLineDash: [4, 8],
selectionOpacity: 1,
selectionShadowColor: '#d3d3d3',
selectionShadowBlur: 10,
selectionShadowOffsetX: 10,
selectionShadowOffsetY: 10,
selectionCursor: 'pointer',
},
},
},
});

track

Configure slider track styles.

PropertyDescriptionTypeDefaultRequired
trackLengthTrack lengthnumber-
trackSizeTrack sizenumber16
trackFillTrack fill colorstring#416180
trackFillOpacityTrack fill opacitynumber1
trackStrokeTrack stroke colorstring-
trackStrokeOpacityTrack stroke opacitynumber-
trackLineWidthTrack stroke widthnumber-
trackLineDashTrack stroke dash configuration[number,number]-
trackOpacityTrack overall opacitynumber-
trackShadowColorTrack shadow colorstring-
trackShadowBlurTrack shadow blur coefficientnumber-
trackShadowOffsetXTrack shadow horizontal offsetnumber-
trackShadowOffsetYTrack shadow vertical offsetnumber-
trackCursorTrack cursor stylestringdefault

When configuring selection styles in the Slider component, use the track prefix with properties instead of object configuration.

({
slider: {
x: {
// Can be configured outside style as well, G2 internally handles compatibility
style: {
trackSize: 20,
trackFill: '#000',
trackFillOpacity: 0.9,
trackStroke: '#DAF5EC',
trackStrokeOpacity: 0.9,
trackLineWidth: 2,
trackLineDash: [4, 8],
trackOpacity: 1,
trackShadowColor: '#d3d3d3',
trackShadowBlur: 10,
trackShadowOffsetX: 10,
trackShadowOffsetY: 10,
trackCursor: 'pointer',
},
},
},
});

handle

Configure slider handle styles.

PropertyDescriptionTypeDefaultRequired
handleLabelFontSizeHandle label font sizenumber12
handleLabelFontFamilyHandle label font familystring-
handleLabelFontWeightHandle label font weightnumbernormal
handleLabelLineHeightHandle label line heightnumber-
handleLabelTextAlignSet current alignment for handle label text contentcenter | end | left | right | startstart
handleLabelTextBaselineSet current text baseline used when drawing handle label texttop | middle | bottom | alphabetic | hangingbottom
handleLabelFillHandle label font colorstring#1D2129
handleLabelFillOpacityHandle label font color opacitynumber0.45
handleLabelStrokeHandle label font stroke colorstring-
handleLabelStrokeOpacityHandle label font stroke color opacitynumber-
handleLabelLineWidthHandle label font stroke widthnumber-
handleLabelLineDashHandle label font stroke dash configuration. First value is dash segment length, second is gap distance. Setting [0,0] removes stroke.[number , number]-
handleLabelOpacityHandle label text overall opacitynumber-
handleLabelShadowColorHandle label text shadow colorstring-
handleLabelShadowBlurHandle label text shadow Gaussian blur coefficientnumber-
handleLabelShadowOffsetXShadow horizontal distance from handle label textnumber-
handleLabelShadowOffsetYShadow vertical distance from handle label textnumber-
handleLabelCursorHandle label cursor style. Same as CSS cursor stylestringdefault
handleIconRadiusHandle icon corner radiusnumber2
handleIconSizeHandle icon sizenumber10
handleIconFillHandle icon fill colorstring#f7f7f7
handleIconFillOpacityHandle icon fill opacitynumber1
handleIconStrokeHandle icon strokestring#1D2129
handleIconStrokeOpacityHandle icon stroke opacitynumber0.25
handleIconLineWidthHandle icon stroke widthnumber1
handleIconLineDashHandle icon stroke dash configuration. First value is dash segment length, second is gap distance. Setting [0,0] removes stroke.[number , number]-
handleIconOpacityHandle icon overall opacitynumber-
handleIconShadowColorHandle icon shadow colorstring-
handleIconShadowBlurHandle icon shadow Gaussian blur coefficientnumber-
handleIconShadowOffsetXShadow horizontal distance from handle iconnumber-
handleIconShadowOffsetYShadow vertical distance from handle iconnumber-
handleIconCursorHandle icon cursor style. Same as CSS cursor stylestringdefault

When configuring slider handle properties in the Slider component, use the handle prefix with properties instead of object configuration.

({
slider: {
x: {
// Can be configured outside style as well, G2 internally handles compatibility
style: {
// 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',
},
},
},
});

sparkline

Configure slider sparkline styles.

PropertyDescriptionTypeDefaultRequired
sparklineTypeSparkline type: line chart, column chartline | columnline
sparklineIsStackWhether to stack databooleanfalse
sparklineRangeSpecify value range. If not specified, will use data's min and max values[number, number]-
sparklineColorSpecify colorstring | string[] | (index: number)=>string-
sparklineSmoothFor line charts, smooth curvesbooleanfalse
sparklineLineStrokeFor line charts, line colorstring-
sparklineLineStrokeOpacityFor line charts, line opacitynumber-
sparklineLineLineDashFor line charts, line dash configuration. First value is dash segment length, second is gap distance. Setting [0, 0] removes stroke.[number,number]-
sparklineAreaFillFor line charts, fill area colorstring-
sparklineAreaFillOpacityFor line charts, fill area opacitynumber-
sparklineColumnFillFor column charts, column colorstring-
sparklineColumnFillOpacityFor column charts, column opacitynumber-
sparklineIsGroupFor column charts, whether to display in groupsbooleanfalse
sparklineSpacingFor column charts, spacing between grouped columnsnumber0

When configuring sparkline properties in the Slider component, use the sparkline prefix with properties instead of object configuration.

({
slider: {
x: {
// Can be configured outside style as well, G2 internally handles compatibility
style: {
sparklineType: 'line',
sparklineColor: 'red',
},
},
},
});

Events

PropertyDescriptionType
valuechangeTriggered when selection changes, listen via events({detail: { value: any; }}) => void
import { Chart } from '@antv/g2';
const chart = new Chart({
container: 'container',
});
chart
.line()
.data({
type: 'fetch',
value:
'https://gw.alipayobjects.com/os/bmw-prod/551d80c6-a6be-4f3c-a82a-abd739e12977.csv',
})
.encode('x', 'date')
.encode('y', 'close')
// Enable X-axis slider
.slider('x', {});
chart.on('afterrender', () => {
const { canvas } = chart.getContext();
const { document } = canvas;
document.querySelector('.slider').addEventListener('valuechange', (evt) => {
console.info(evt.detail);
});
});
chart.render();

Examples

Custom Slider

If you don't want to use G2's default slider, you can customize a drag axis following these steps:

  • Render the slider after rendering is complete.
  • Listen to slider events.

The key to the first step is determining the slider's position and length through the coordinate object obtained via chart.getCoordinate. The key to the second step is using the scale obtained through chart.getScale to invert the selected range, finally obtaining the selected data range, then updating the scale's domain.

(() => {
function sliderX(chart) {
// Create and mount range
const container = chart.getContainer();
const range = document.createElement('input');
container.append(range);
// Set range width and other properties based on coordinate
const coordinate = chart.getCoordinate();
const { paddingLeft, width } = coordinate.getOptions();
range.type = 'range';
range.min = 0;
range.max = width;
range.value = width;
range.style.display = 'block';
range.style.width = width + 'px';
range.style.marginLeft = paddingLeft + 'px';
// Listen to change event, get filtered domain through scale
// Update domain and render
const scale = chart.getScaleByChannel('x');
const options = chart.options();
range.onchange = (event) => {
const value = event.target.value;
const range = [0, value / width];
const domain = range.map((d) => scale.invert(d));
chart.options({
...options,
scale: { x: { domain } },
});
chart.render();
};
}
const container = document.createElement('div');
const chart = new G2.Chart({ container });
chart.options({
type: 'line',
data: {
type: 'fetch',
value:
'https://gw.alipayobjects.com/os/bmw-prod/551d80c6-a6be-4f3c-a82a-abd739e12977.csv',
},
encode: { x: 'date', y: 'close' },
});
chart.render().then(sliderX);
return chart.getContainer();
})();