Scatter

6 min read

Plot Container

width

optional number default: 400

Set the width of the chart.

height

optional number default: 400

Set the height of the chart.

autoFit

optional boolean default: true

Whether the chart automatically adjusts to fit the container. If it is set to true, width and height configuration would fail.

padding

optional number[] | number | 'auto'

Set padding value of the canvas. You can also use auto.

appendPadding

optional number[] | number

Extra appendPadding value.

renderer

optional string default: canvas

Set the render way to canvas or svg.

pixelRatio

optional number default: window.devicePixelRatio

Set the pixel ratio of the chart.

limitInPlot

optional boolean

Whether clip the Geometry beyond the coordinate system。

supportCSSTransform

optional boolean

支持 CSS transform,开启后图表的交互以及事件将在页面设置了 css transform 属性时生效,默认关闭。

useDeferredLabel

optional boolean|number

开启后 label 渲染会在浏览器空闲时机执行。可制定具体 number 数值,来限定 timeout 时间 (建议开启时,指定 timeout 时间)

locale

optional string

Specify the locale. There are two built-in locales: 'zh-CN' and 'en-US'. Or you can use G2Plot.registerLocale to register a new locale. Go src/locales/en_US.ts to see the format.

Data Mapping

data

required array object

Configure the data source. The data source is a collection of objects. For example:[{ time: '1991',value: 20 }, { time: '1992',value: 20 }]

xField

required string

The name of the data field corresponding to the graph in the x direction, usually the field corresponding to the horizontal coordinate axis. For example, to see how many people are in different classes, the class field is the corresponding xField.

yField

required string

The name of the data field corresponding to the graph in the y direction, usually the field corresponding to the vertical coordinate axis. For example, to see the number of students in different classes, the number field is the corresponding yField.

meta

optional object

Configure the meta of each data field of the chart in global, to define the type and presentation of data. Configuration of the meta will affect the text content of all components.

PropertiesTypeDescription
aliasstringalias of the data field
formatterfunctioncallback function to format all values of the data field
valuesstring[]enumerate all the values of the data field
rangenumber[]mapping range of the data field, default: [0,1]

See also the Meta Options to learn more about configuration of meta.

const data = [
  { country: 'Asia', year: '1750', value: 502 },
  { country: 'Asia', year: '1800', value: 635 },
  { country: 'Europe', year: '1750', value: 163 },
  { country: 'Europe', year: '1800', value: 203 },
];

const scatterPlot = new Scatter('container', {
  data,
  meta: {    year: {      alias: '年份',      range: [0, 1],    },    value: {      alias: '数量',      formatter: (v) => {        return `${v}`;      },    },  },  xField: 'year',
  yField: 'value',
  colorField: 'country',
});
scatterPlot.render();

type

optional jitter | stack | symmetric | dodge default: jitter

Adjust the data. Adjust types provided by G2Plot includes 'stack', 'dodge' 'jitter', 'symmetric'. Not recommended to modify.

colorField

optional string

The name of the data field corresponding to the dot color map.

shapeField

optional string

The name of the data field corresponding to the dot shape map.

sizeField

optional string

The name of the data field corresponding to the point size map.

Geometry Style

color

optional string | string[] | Function

Configure the color. If there is no colorField configured, set one single color. Otherwise you can set a series of colors, or you can use callback function.

Default: The color board of the theme.

// set one single color
{
  color: '#a8ddb5'
}
// set a series of colors
{
  colorField: 'type', // or seriesField in some cases
  color: ['#d62728', '#2ca02c', '#000000'],
}
// Function
{
  colorField: 'type', // or seriesField in some cases
  color: ({ type }) => {
    if(type === 'male'){
      return 'red';
    }
    return 'yellow';
  }
}

size

optional _number | [number, number] | Function_

Specifies the size of the point. If no sizeField is configured, specify one. When the Sizefiled is configured, the size array '[minSize, maxSize]' can be specified, or the corresponding value can be set through the callback function method.

// Set a single size
{
  size: 10
}
// size range
{
  sizeField: 'weight',
  size: [2, 10],
}
// Function
{
  sizeField: 'weight',
  size: (weight) => {
    // TODO
    return Math.floor(weight / 100);
  }
}

shape

optional _string | string[] | Function_

Specifies the size of the point. If no sizeField is configured, specify one. When the Sizefiled is configured, the size array '[minSize, maxSize]' can be specified, or the corresponding value can be set through the callback function method.

Built-in shape: circle, square, bowtie, diamond, hexagon, triangle,triangle-down, hollow-circle, hollow-square, hollow-bowtie,hollow-diamond, hollow-hexagon, hollow-triangle, hollow-triangle-down, cross, tick, plus, hyphen, line.

// Set a single size
{
  shape: 'square'
}
// The size of the range
{
  shapeField: 'gender',
  shape: ['circle', 'square'],
}
// Function
{
  shapeField: 'gender',
  shape: (gender) => {
    if(type === 'male'){
      return 'circle';
    }
    // TODO
    return 'square';
  },
}

pointStyle

optional object

Set polyline styles. The 'fill' in pointStyle overrides the configuration of 'color'. PointStyle can be specified either directly or via a callback to specify a separate style based on the data.

Default configuration:

PropertiesTypeDescription
fillstringFill color
strokestringStroke color
lineWidthnumberLine width
lineDashnumberThe dotted lines show
opacitynumberTransparency
fillOpacitynumberFill transparency
strokeOpacitynumberStroke transparency
// Specified directly
{
  pointStyle: {
    fill: 'red',
    stroke: 'yellow',
    opacity: 0.8
  },
}
// Function
{
  pointStyle: (x, y, colorField) => {
    if (colorField === 'male') {
      return {
        fill: 'green',
        stroke: 'yellow',
        opacity: 0.8,
      }
    }
    // TODO
    return {
      fill: 'red',
      stroke: 'yellow',
      opacity: 0.8,
    }
  }
}

Plot Components

tooltip

fields
optional string[]

Specifies the fields to be displayed in the Tooltip. By default, different charts have different default field lists. Use with the 'formatter' configuration for more effect.

tooltip: {
  fields: ['x', 'y'],
}
formatter
optional Function

Formats the contents of the Tooltip Item (you can use customContent when content contains multiple tooltipItems).

tooltip: {
  formatter: (datum: Datum) => {
    return { name: datum.x, value: datum.y + '%' };
  },
}
follow
optional boolean default: true

Sets whether the Tooltip content box follows the mouse.

enterable
optional boolean default: false

Whether the tooltip allows mouse to slide in.

showTitle
optional boolean default: false

Whether show tooltip title.

title
optional string

Set the title content of the Tooltip: If the value is the name of the data field, the value for the field in the data is displayed, and if the field does not exist in the data, the title value is displayed directly.

position
optional top | bottom | left | right

Sets the fixed display location of the Tooltip relative to the data point.

shared
optional boolean

True means that all data corresponding to the current point is merged and displayed, while false means that only the data content closest to the current point is displayed.

showCrosshairs
optional boolean default: false

Whether show crosshairs。

crosshairs
optional object

Configure tooltip crosshairs to work if and only if 'showCrosshairs' is true.

PropertiesTypeDescription
type'x' | 'y' | 'xy'Crosshairs Type: 'X' represents the auxiliary line on the X axis, 'Y' on the Y axis
linelineStyleThe configuration item for line, see more ShapeAttrs
textTooltipCrosshairsText | TooltipCrosshairsTextCallbackText configuration of crosshairs pointer, support callback
textBackgroundtextBackgroundStyleGuideline text background configuration
followbooleanWhether the guide line follows the mouse. Default is false, that is, to locate the data point

TooltipCrosshairsText 类型定义如下:

/** 辅助线文本配置 */
type TooltipCrosshairsText = {
  /**
   * 文本位置,只支持 start, end
   * @type {string}
   */
  position?: string;
  /**
   * 文本内容
   */
  content?: string;
  /**
   * 距离线的距离
   * @type {number}
   */
  offset?: number;
  /**
    * 是否自动旋转
    * @type {boolean}
    */
  autoRotate?: boolean;
  /**
    * 文本的配置项
    * @type {ShapeAttrs}
    */
  style?: TextStyle;
}

其中,TextStyle 类型定义详见: 通用文本样式

TooltipCrosshairsTextCallback 类型定义如下:

/**
 * 辅助线文本回调函数
 * @param type 对应当前 crosshairs 的类型,值为 'x' 或者 'y'
 * @param defaultContent 对应当前 crosshairs 默认的文本内容
 * @param items 对应当前 tooltip 内容框中的数据
 * @param currentPoint 对应当前坐标点
 * @returns 返回当前 crosshairs 对应的辅助线文本配置
 */
type TooltipCrosshairsTextCallback = (type: string, defaultContent: any, items: any[], currentPoint: Point) => TooltipCrosshairsText;

TextBackgroundStyle

PropertiesTypeDescription
paddingnumber | number[]White space around the background of a text
styleshapeStyleThe configuration item for line, see more ShapeAttrs
showMarkers
optional boolean default: true

Whether to render TooltipMarkers.

marker
optional ShapeAttrs

TooltipMarker style configuration.

Please refer to the style configuration ShapeAttrs

showContent
optional boolean default: false

Whether to display the Tooltip content box.

container
optional string|HTMLElement

Custom tooltip container.

containerTpl
optional string

Templates used to specify the legend container must include the classes of each DOM node when customizing the template

itemTpl
optional string

The default template for each record, which must include the classes of each DOM node when customizing the template.

domStyles
optional TooltipDomStyles

The styles for each DOM.

dom-styles
/** Tooltip content box css style */
{
  domStyles: {
    'g2-tooltip'?: CSSProperties;
    'g2-tooltip-title'?: CSSProperties;
    'g2-tooltip-list'?: CSSProperties;
    'g2-tooltip-list-item'?: CSSProperties;
    'g2-tooltip-marker'?: CSSProperties;
    'g2-tooltip-value'?: CSSProperties;
    'g2-tooltip-name'?: CSSProperties;
  }
}
offset
optional number

Tooltip offset.

reversed
optional boolean

是否将 tooltip items 逆序.

showNil
optional boolean

是否显示空值的 tooltip 项

customItems ✨
optional Function

在 tooltip 渲染之前,对最终的 items 进行自定义处理(比如排序、过滤、格式化等)。

{
  tooltip: {
    customItems: (originalItems: TooltipItem[]) => {
      // process originalItems, 
      return originalItems;
    };
  }
}
customContent
optional Function

Support for custom templates. Live demo

{
  tooltip: {
    customContent: (title, data) => {
      return `<div>${title}</div>`;
    };
  }
}

label

PropertiesTypeDescription
typestringWhen a user uses a custom label type, need to declare the specific type, otherwise you will use the default label type rendering (pie chart label support inner | outer | spiders)
offsetnumberlabel offset
offsetXnumberThe offset distance of the label from the data point in the X direction
offsetYnumberThe offset distance of the label from the data point in the Y direction
contentstring | IGroup | IShape | GeometryLabelContentCallbackText content that is displayed, if not declared, is displayed according to the value of the first field participating in the mapping
styleShapeAttrsLabel text graphic property style
autoRotatestringWhether to rotate automatically, default true
rotatenumberText rotation angle, unit is radian, clockwise rotation
labelLinenull | boolean | LabelLineCfgUsed to set the style property of the text connector. NULL indicates that it is not displayed.
labelEmitbooleanOnly applies to text in polar coordinates, indicating whether the text is radially displayed according to the angle. True means on and false means off
layout'overlap' | 'fixedOverlap' | 'limitInShape'Text layout type, support a variety of layout function combination.
position'top' | 'bottom' | 'middle' | 'left' | 'right'Specifies the position of the current Label relative to the current graphic (💡 Attention: Only works for column plot and bar plot, which geometry is interval)
animateboolean | AnimateOptionAnimation configuration.
formatterFunctionFormat function
autoHidebooleanWhether to hide it automatically, default to false

Types of LabelLineCfg are as follow: (Go ShapeAttrs see more details about ShapeAttrs)

type LabelLineCfg = {
  style?: ShapeAttrs;
}

Example code:

{
  label: {
    style: {
      fill: 'red',
      opacity: 0.6,
      fontSize: 24
    }
  }
}

axis

Same for xAxis and yAxis. Note: Since DualAxes or BidirectionalBar has double Y-axes, the yAxis is a object which takes the field in yField as the 'key'.

top
optional boolean default: false

是否渲染在画布顶层,防止部分图形中,需要将 axis 显示在图形上面,避免被图形遮挡。

position
optional top | bottom | left | right

For Cartesian coordinates, set the position of the coordinate axes.

title
optional object

A configuration item for the title, NULL means not to be displayed.

PropertiesTypeDescription
textstringThe title of axis
positionstringPosition of the axis title, default: 'center'. Options: start, center, end
offsetnumberThe distance of the title from the coordinate axis
spacingnumberThe distance between the title and the text on the coordinate axis
styleshapeStyleTitle text configuration items
autoRotatebooleanWhether to rotate automatically or not, default: true
rotationnumber关闭 autoRotate 后,可以设置自动旋转的角度,如: -Math.PI / 2 (条形图 y 轴标题)

shapeStyle

PropertiesTypeDescription
fillstringFill color of the shape
rnumberused in point, means the radius of geometry
fillOpacitynumberFill opacity of the shape
strokestringStroke color of the shape
lineWidthnumberThe width of the stroke of the shape
lineDash[number,number]Configure dashed line stroke. The first parameter is the length of each segment, and the second parameter is the gap between segment. When lineDash is set to [0,0], there is no effect.
lineOpacitynumberOpacity of the stroke
opacitynumberOpacity of the shape
shadowColorstringShadow color of the shape
strokeOpacitynumberStroke opacity of the shape
shadowBlurnumberGaussian blur coefficient of the shadow
shadowOffsetXnumberConfigure horizontal distance between shadow and shape
shadowOffsetYnumberConfigure vertical distance between shadow and shape
cursorstringMouse style, same as the mouse style of CSS, default value : 'default'

Example:

{
  style: {
    fill: 'red',
    fillOpacity: 0.5,
    stroke: 'black',
    lineWidth: 1,
    lineDash: [4, 5],
    strokeOpacity: 0.7,
    shadowColor: 'black',
    shadowBlur: 10,
    shadowOffsetX: 5,
    shadowOffsetY: 5,
    cursor: 'pointer'
  }
}

More documents about ShapeStyle, see Graphic Style.

label

optional object

A configuration item for the text label. NULL indicates that it is not displayed.

PropertiesTypeDescription
typestringWhen a user uses a custom label type, need to declare the specific type, otherwise you will use the default label type rendering (pie chart label support inner | outer | spiders)
offsetnumberlabel offset
offsetXnumberThe offset distance of the label from the data point in the X direction
offsetYnumberThe offset distance of the label from the data point in the Y direction
contentstring | IGroup | IShape | GeometryLabelContentCallbackText content that is displayed, if not declared, is displayed according to the value of the first field participating in the mapping
styleShapeAttrsLabel text graphic property style
autoRotatestringWhether to rotate automatically, default true
rotatenumberText rotation angle, unit is radian, clockwise rotation
labelLinenull | boolean | LabelLineCfgUsed to set the style property of the text connector. NULL indicates that it is not displayed.
labelEmitbooleanOnly applies to text in polar coordinates, indicating whether the text is radially displayed according to the angle. True means on and false means off
layout'overlap' | 'fixedOverlap' | 'limitInShape'Text layout type, support a variety of layout function combination.
position'top' | 'bottom' | 'middle' | 'left' | 'right'Specifies the position of the current Label relative to the current graphic (💡 Attention: Only works for column plot and bar plot, which geometry is interval)
animateboolean | AnimateOptionAnimation configuration.
formatterFunctionFormat function
autoHidebooleanWhether to hide it automatically, default to false

Types of LabelLineCfg are as follow: (Go ShapeAttrs see more details about ShapeAttrs)

type LabelLineCfg = {
  style?: ShapeAttrs;
}

Example code:

{
  label: {
    style: {
      fill: 'red',
      opacity: 0.6,
      fontSize: 24
    }
  }
}
label
AxisLabelCfg | null optional

Configurations related to axis label. Set this to null to prevent the axis label from appearing. The details of AxisLabelCfg are as follows:

PropertiesType
styleShapeAttrs-Axis label text graphic property style
offsetnumber-Axis label offset
rotatenumber-Axis label text rotation angle
autoRotateboolean |avoidCallbacktrueWhether to rotate automatically, default true
autoHideboolean |avoidCallback | { type:string,cfg?:AxisLabelAutoHideCfg }falseWhether to hide it automatically, default to false
autoEllipsisbooleanfalseWhether to ellipsis label when overflow, default to false
formatter(text: string, item: ListItem, index: number) => anyfalseFormat function

avoidCallback 类型定义如下:

type avoidCallback = (isVertical: boolean, labelGroup: IGroup, limitLength?: number) => boolean;

AxisLabelAutoHideCfg 类型定义如下:

interface AxisLabelAutoHideCfg {
  /** 最小间距配置 */
  minGap?: number;
  type?: string;
}

如果你需要强制最后一个 tick 展示,可以尝试这么设置

{
  scale: {
    [xField 对应的值]: {
      showLast: true,
    }
  },
  xAxis: {
    // 设置默认不自动隐藏,或
    // autoHide: false,
    autoHide: {
      type: 'equidistantceWithReverseBoth'
    }
  }
}
verticalFactor
optional number

Mark the direction of the label on the axis, with 1 to the left and -1 to the right (Only works in vertical axis).

verticalLimitLength
optional number

Configuring the maximum limit length in the vertical direction of the coordinate axis has a significant impact on text adaptation.

grid
optional object

Axis grid line configuration item. NULL means not shown.

PropertiesTypeDescription
linelineStyleThe style of the line
alternateColorstring|string[]The fill color between two grid lines
closedbooleanWhether to close the grid for circle
alignTickbooleanIf the value is false, it will be displayed between the two scales

Then config of grid.line is the same as: line

line
optional object

Coordinate axis configuration item, NULL means not displayed.

Attention: The full configuration of lineStyle is { style: { stroke: '#ddd', ... } }, please check it when your configuration doesn't work.

PropertiesTypeDescription
strokestringcolor of the line
lineWidthnumberwidth of the line
lineDash[number,number]configure dashed line, the first parameter is the length of each segment, the second parameter is the gap between segment. When lineDash is set to [0,0], there is no effect.
opacitynumberopacity
shadowColorstringshadow color
shadowBlurnumberGaussian blur coefficient
shadowOffsetXnumberconfigure horizontal distance between shadow and line
shadowOffsetYnumberconfigure vertical distance between shadow and line
cursorstringmouse style, same as the mouse style of CSS, default value : 'default'

Example (config the grid line style of xAxis):

{
  xAxis: {
    grid: {
      line: {
        style: {
          stroke: 'black',
          lineWidth: 2,
          lineDash: [4, 5],
          strokeOpacity: 0.7,
          shadowColor: 'black',
          shadowBlur: 10,
          shadowOffsetX: 5,
          shadowOffsetY: 5,
          cursor: 'pointer'
        }
      }
    }
  }
}
tickLine
optional object

The configuration item of the coordinate axis scale line. NULL means not displayed.

PropertiesTypeDescription
stylelineStyleThe style of tickLine.
alignTickbooleanWhether aligh tickLine with tick label
lengthnumberThe length of tickLine.

Go ShapeAttrs see more details about ShapeAttrs. The params of ShapeAttrsCallback are as follow:

type ShapeAttrsCallback = (item: any, index: number, items: any[]) => ShapeAttrs;
subTickLine
optional object

A configuration item for a coordinate subscale. NULL indicates that it is not displayed.

PropertiesTypeDescription
styleShapeAttrs | ShapeAttrsCallbackThe style of subTickLine.
countnumberThe count of subTickLine.
lengthnumberThe length of subTickLine.

Go ShapeAttrs see more details about ShapeAttrs. The params of ShapeAttrsCallback are as follow:

type ShapeAttrsCallback = (item: any, index: number, items: any[]) => ShapeAttrs;
nice
optional boolean default: true

Whether to nice.

min
optional number default: 0

Minimum axis.

max
optional number

Maximum axis.

minLimit
optional number

Minimal limit.

maxLimit
optional number

Maximum limit.

tickCount
optional number

The expected number of axes, not the final result.

tickInterval
optional number

Interval of axes.

tickMethod
optional string | Function default: false

Specify a tick calculation method, or customize a tick calculation method. Built-in tick calculations include cattime-catwilkinson-extendedr-prettytimetime-prettylogpowquantiled3-linear

animate
optional boolean default: true

Animation switch, default true.

animateOption
optional object

Animation parameter configuration.

interface ComponentAnimateCfg {
  /** Duration of the first animation */
  readonly duration?: number;
  /** Easing method used for the first animation. */
  readonly easing?: string;
  /** Delay before updating the animation */
  readonly delay?: number;
}
// Configure the reference
{
  animateOption: {
    appear: ComponentAnimateCfg;
    update: ComponentAnimateCfg;
    enter: ComponentAnimateCfg;
    leave: ComponentAnimateCfg;
  }
}

legend

optional false | LegendCfg
When colorField existed and legend is not false, color legend will be rendered.
When shapeField existed and legend is not false, shape legend will be rendered. You can set `shapeLegend: false` to hide shape legend.

There are two ways to configure legends

Method 1, pass in 'Boolean' to set whether to display a legend.

legend: false; // close legend

Method 2, pass in LegendCfg to configure the legend as a whole.

legend: {
  layout: 'horizontal',
  position: 'right'
}
layout
optional horizontal | vertical

Layout of legend.

title
optional G2LegendTitleCfg

Legend title configuration is not displayed by default. G2LegendTitleCfg Configuration is as follows:

PropertiesTypeDefaultDescription
titlestringContent of legend title
spacingnumber-The spacing between the title and the legend item
styleobject-Text style configuration item, refer to Graphic Style
position
optional string

The position of legend is optional:'top', 'top-left', 'top-right', 'left', 'left-top', 'left-bottom', 'right', 'right-top', 'right-bottom', 'bottom', 'bottom-left', 'bottom-right'。

offsetX
optional number

Legends offset in the x direction.

offsetY
optional number

Legends offset in the y direction.

background
optional LegendBackgroundCfg

Background box configuration item. LegendBackgroundCFG is configured as follows:

PropertiesTypeDescription
paddingnumber | number[]White space in the background
styleShapeAttrBackground style configuration, Reference Graphic Style
flipPage
optional boolean
Apply to Classification legend,whether to page when there are too many legend items. (⚠️ 暂不支持多行展示分页)
maxRow
number optional
Apply to Classification legend. You can set the maximum number of rows when legend items is flip-paged, (only applicable to 'layout:' horizontal '),default: 1.
optional object
Apply to Classification legend, configure the style of page navigator, it works when legend is in flipPage. Types of LegendPageNavigatorCfg are as follow:
PropertiesTypeDescription
marker.stylePageNavigatorMarkerStyle分页器指示箭头配置项
text.stylePageNavigatorTextStyleThe text style of page info.

Types of PageNavigatorMarkerStyle are as follow:

PropertiesTypeDefaultDescription
inactiveFillstring-Fill color of arrow marker when unclickable (inactive status).
inactiveOpacitynumber-Fill opacity of arrow marker when unclickable (inactive status).
fillstring-Default fill color of arrow marker (active status).
opacitynumber-Default fill opacity of arrow marker (active status).
sizenumber-Size of arrow marker.

Types of PageNavigatorTextStyle are as follow:

PropertiesTypeDefaultDescription
fillstring-Font color of page navigator info.
fontSizenumber-Font size of page navigator info.

Example:

pageNavigator: {
  marker: {
    style: {
      // 非激活,不可点击态时的填充色设置
      inactiveFill: '#000',
      inactiveOpacity: 0.45,
      // 默认填充色设置
      fill: '#000',
      opacity: 0.8,
      size: 12,
    },
  },
  text: {
    style: {
      fill: '#ccc',
      fontSize: 8,
    },
  },
},
itemHeight
optional number default: null
Apply to Classification legend, lengend item height, default null。
itemWidth
optional number default: null
Apply to Classification legend, legend item width, default null, automatic calculation.
itemName
optional LegendItemNameCfg
适用于 分类图例,图例项 name 文本的配置。LegendItemNameCfg 配置如下:
参数名类型默认值描述
style((item: ListItem, index: number, items: ListItem[]) => ShapeAttrs) | ShapeAttrs-
spacingnumber-
formatter(text: string, item: ListItem, index: number) => any;

其中, ShapeAttrs 详细配置见:文档ListItem 配置如下:

type ListItem = {
  /**
   * 名称 {string}
   */
  name: string;
  /**
   * 值 {any}
   */
  value: any;
  /**
   * 图形标记 {object|string}
   */
  marker?: Marker | string;
}

type Marker = {
  symbol? string;
  style?: ShapeAttrs;
  spacing?: number;
};
itemValue
optional LegendItemValueCfg
适用于 分类图例,图例项 value 附加值的配置项。LegendItemValueCfg 配置如下:
参数名类型默认值描述
alignRightbooleanfalse是否右对齐,默认为 false,仅当设置图例项宽度时生效
formatterfunction-格式化函数, (text: string, item: ListItem, index: number) => any;
style((item: ListItem, index: number, items: ListItem[]) => ShapeAttrs) | ShapeAttrs-

其中, ShapeAttrs 详细配置见:文档ListItem 配置如下:

type ListItem = {
  /**
   * 名称 {string}
   */
  name: string;
  /**
   * 值 {any}
   */
  value: any;
  /**
   * 图形标记 {object|string}
   */
  marker?: Marker | string;
}

type Marker = {
  symbol? string;
  style?: ShapeAttrs;
  spacing?: number;
};
itemSpacing
optional number
Apply to Classification legend, control the horizontal spacing of legend items.
itemMarginBottom
optional number
Apply to Classification legend, control the vertical spacing of legend items.
label
optional ContinueLegendLabelCfg
Apply to Continuous legend, a configuration item for the text, ContinueLegendLabelCfg Configuration is as follows:
PropertiesTypeDefaultDescription
alignstring-The alignment of text with the slider
- rail : Align with the slide rail, at both ends of the slide rail
- top, bottom: Legends are valid when laid out horizontally
- left, right: Legends are valid when laid out vertically
styleobject-Text style configuration item, reference Graphic Style
spacingnumber-The distance between the text and the slide
formatter(value: any) => string文本的格式化方式
marker
optional MarkerCfg
Apply to Classification legend, the configuration of the Marker icon of the legend item.
PropertiesTypeDefaultDescription
symbolMarker | MarkerCallback-The symbol shape of a legend marker is configured
styleShapeAttrs-The configuration item of legend item Marker
spacingnumber-The spacing between legend item marker and the following name

Marker The supported tag types are: circle | square | line | diamond | triangle | triangle-down | hexagon | bowtie | cross | tick | plus | hyphenMarkerCallback is (x: number, y: number, r: number) => PathCommand

DEMO of Customize legend marker.

radio ✨
optional RadioCfg
适用于 分类图例,图例项的末尾展示一个 radio 的按钮 🔘,点击可以实现“图例正选”筛选(聚焦)。
type RadioCfg = { style: ShapeAttr };
maxItemWidth
number optional
适用于 分类图例,图例项最大宽度设置。
maxWidthRatio
number optional. 取值范围:[0, 1], 默认: 0.25
适用于 分类图例,图例项容器最大宽度比例(以 view 的 bbox 容器大小为参照)设置,如果不需要该配置,可以设置为 null
maxHeightRatio
number optional. 取值范围:[0, 1], 默认: 0.25
适用于 分类图例,图例项容器最大高度比例(以 view 的 bbox 容器大小为参照)设置,如果不需要该配置,可以设置为 null
maxWidth
optional number
Apply to Classification legend, the maximum width of the legend item. 当 layout 等于 'horizontal' 时,生效,当图例项横向排布,超过最大宽度时,会结合 flipPage: true 进行分页。
maxHeight
optional number
Apply to Classification legend, the maximum height of the legend item. 当 layout 等于 'vertical' 时,生效,当图例项纵向排布,超过最大高度时,会结合 flipPage: true 进行分页。
reversed
optional boolean Apply to Classification legend, whether to display legend items in reverse order.
custom
optional boolean

If it is a custom legend, the items property needs to be declared when this property is true.

items
optional LegendItem[] Apply to Classification legend, the user configures the content of the legend item. LegendItem Configuration is as follows:
PropertiesTypeRequiredDescription
idstringUnique value for animation or lookup
namestringrequiredname
valueanyrequiredvalue
markerMarkerCfgmarker
PropertiesTypeDefaultDescription
symbolMarker | MarkerCallback-The symbol shape of a legend marker is configured
styleShapeAttrs-The configuration item of legend item Marker
spacingnumber-The spacing between legend item marker and the following name

Marker The supported tag types are: circle | square | line | diamond | triangle | triangle-down | hexagon | bowtie | cross | tick | plus | hyphenMarkerCallback is (x: number, y: number, r: number) => PathCommand

DEMO of Customize legend marker.

min
optional number
Apply to Continuous legend, select the minimum value of the range.
max
optional number
Apply to Continuous legend, select the maximum value of the range.
value
optional number[]
Apply to Continuous legend, 当前选中的范围.
selected ✨ 🆕
object optional

图例高亮状态,false 表示默认置灰,默认不设置或为 true 表示高亮,会同步进行数据的筛选展示。

示例:

legend: {
  selected: {
    '分类一': true,
    '分类二': false,
    '分类三': false,
  }
}
slidable
optional boolean default: true Apply to Continuous legend, whether the slider can slide.
rail
optional ContinueLegendRailCfg Apply to Continuous legend, a style configuration item for the legend slider (background).ContinueLegendRailCfg Configuration is as follows:
PropertiesTypeDefaultDescription
typestring-rail type: color and size, default: 'color'
sizenumber-The width of the slide rail
defaultLengthnumber-The default length of the slider, default: 100. When maxWidth,maxHeight is limited, this property is not used and the length is automatically calculated
styleobject-Slide rail style, refer to Graphic Style
rail.type='color'rail.type='size
colorsize
track
optional ContinueLegendTrackCfg Apply to Continuous legend, select the color block style configuration item for the range. ContinueLegendTrackCfg Configuration is as follows:
PropertiesTypeDefaultDescription
styleobject-Selected range of styles, reference Graphic Style
handler
optional ContinueLegendHandlerCfg Apply to Continuous legend, configuration items for slider. (暂不支持自定义)

ContinueLegendHandlerCfg is configured as follows:

PropertiesTypeDefaultDescription
sizenumber-Slider size, default: 10
styleobject-Slider configuration, reference Graphic Style

shapeLegend

optional false | LegendCfg
当 shapeField 存在时,且 legend 不为 false 以及 shapeLegend 不为 false,默认会渲染 shape 映射图例。

1、你可以通过设置 `shapeLegend: false` 来隐藏 shape 图例。
2、你也可以通过定义 `shapeLegend` 来对 shape 图例进行配置。

Details to see: legend

sizeLegend

optional false | LegendCfg
Default size legend is not shown, only when `sizeField` and `sizeLegend` existed,size legend will be shown。

Details to see: legend

annotations

详细配置见:各 Annotation 配置项说明。

quadrant

DEMO

optional object

Quadrant components.

PropertiesTypeDescription
xBaselinenumberThe quadrant dividing baseline in the x direction, which defaults to 0
yBaselinenumberThe Y direction of the quadrant division base line, the default is 0
lineStyleobjectConfigure the style of the quadrant divider. Configure the reference drawing properties for details
regionStyleobject[]Quadrant style with detailed configuration of reference drawing properties
labelsobject[]Quadrant text configuration, detailed configuration reference drawing properties

regressionLine

DEMO

optional object

Regression line.

PropertiesTypeDescription
typestringThe type of regression line, exp | linear | loess | log | poly | pow | quad
styleobjectConfigure the regression line style. Configure the reference drawing properties for details
algorithmArray<[number, number]> | ((data: any) => Array<[number, number]>)Custom algorithm with a higher priority than type
topbooleanWhether top level display
regressionLine: {
  algorithm: () => {
    return [
      [8, 6],
      [16, 7],
      [24, 7],
    ];
  },
}

Plot Event

On Plot, binding events are removed by ON and OFF method.

// Bind event
plot.on('eventName', callback);
// Bind event, only trigger one time
plot.once('eventName', callback);
// Remove event
plot.off('eventName', callback);

Composition: ${componentName}:${eventName}

Element refers to the type of element to bind to, for example elementlegend-itemaxis-labelmaskplotlegend-item-namereset-button etc.

Events correspond to DOM common events, for example clickmousedownmouseupdblclickmouseentermouseoutmouseovermousemovemouseleavecontextmenu etc. And support mobile events: touchstarttouchmovetouchend

// Plot adds click events to the entire chart area
plot.on('plot:click', (...args) => {
  console.log(...args);
});

// Element to add a click event, element represents the graphic elements, graphical elements, please see: https://g2.antv.vision/en/docs/manual/concepts/element
plot.on('element:click', (...args) => {
  console.log(...args);
});

// Legend adds click events
plot.on('legend-item:click', (...args) => {
  console.log(...args);
});

// Legend name adds click event
plot.on('legend-item-name:click', (...args) => {
  console.log(...args);
});

// 给 tooltip 添加点击事件
plot.on('tooltip:show', (...args) => {
  console.log(...args);
});

plot.on('tooltip:hide', (...args) => {
  console.log(...args);
});

plot.on('tooltip:change', (...args) => {
  console.log(...args);
});

// Label adds click events
plot.on('label:click', (...args) => {
  console.log(...args);
});

// Mask adds click events
plot.on('mask:click', (...args) => {
  console.log(...args);
});

// Axis-label adds click events
plot.on('axis-label:click', (...args) => {
  console.log(...args);
});

// Add click events to the annotation
plot.on('annotation:click', (...args) => {
  console.log(...args);
});

Plot Method

render()

Render the chart.

update()

optional

Update chart configuration and overwrite it without comparing difference.

Example:

plot.update({
  ...currentConfig,
  legend: false,
});

Plot Theme

Recommend to use 💄 ThemeSet to customize your theme configurations online.

Built-in Theme

Built-in defaults: 'default' and 'dark'

{
  theme: 'default', // 'dark',
}

Theme attributes

In addition to using the built-in 'default' and 'dark' themes, you can also modify some of the theme content by setting the theme properties.

The following table lists the specific properties on the configuration items that make up the topic:

PropertiesTypeDescription
defaultColorstringTheme color
paddingnumbernumber[]
fontFamilystringChart font
colors10string[]Category color palette, used when the number of categories is less than 10
colors20string[]Category color palette, used when the number of categories is greater than 10
columnWidthRationumberGeneral histogram width ratio, 0-1 range of values
maxColumnWidthnumberMaximum width of histogram, pixel value
minColumnWidthnumberMinimum width of histogram, pixel value
roseWidthRationumberRose width ratio, 0-1 range of value
multiplePieWidthRationumberMultilayer pie and loop ratio, 0-1 range values
geometriesobjectConfigure the style of each shape for each Geometry, including the default style and the style for each state
componentsobjectConfigure theme samples for axes, legends, tooltips, and annotations
labelsobjectConfigure the theme style of the label under Geometry
innerLabelsobjectConfigure Geometry to display the Labels theme style inside the graph
pieLabelsobjectConfigure the theme style of pie chart labels

usage:

{
  theme: {
    colors10: [
      '#FF6B3B',
      '#626681',
      '#FFC100',
      '#9FB40F',
      '#76523B',
      '#DAD5B5',
      '#0E8E89',
      '#E19348',
      '#F383A2',
      '#247FEA',
    ];
  }
}

Theme attributes (StyleSheet)

除了以上介绍的主题属性之外,还可以传入主题样式表来自定义主题。如果你需要对全局主题进行配置的话,对样式风格进行切换,比如更改颜色、字体大小、边框粗细等

usage:

{
  theme: {
    styleSheet: {
      fontFamily: 'Avenir';
    }
  }
}

支持的样式表属性:

PropertiesTypeDescription
backgroundColorstringBackground color
brandColorstringBrand color,默认取 10 色分类颜色色板的第一个颜色
paletteQualitative10stringQualitative palette,分类个数小于 10 时使用
paletteQualitative20stringQualitative palette,分类个数大于 10 时使用
paletteSemanticRedstringSemantic red
paletteSemanticGreenstringSemantic green
paletteSemanticYellowstringSemantic yellow
fontFamilystringfontFamily

Update theme

usage:

// example 1:
plot.update({ theme: 'dark' });

// example 2:
plot.update({ theme: { defaultColor: '#FF6B3B' } });

Custom theme

In addition, G2 provides a custom topic mechanism to define a new topic structure, allowing users to switch and define chart topics. Go G2 | Custom theme for more details.

🌰 Customize theme DEMO

Plot Interactions

Built-in interactions of scatter are as follows:

InteractionDescriptionConfiguration
brush用于刷选交互,配置该交互后,可进行刷选。brush: { enabled: true }

brush

optional BrushCfg

Configuration of brush interaction.

Properties

Types of BrushCfg are as follows:

PropertiesTypeDescription
enabledboolean是否开启 brush 刷选交互,默认为:'false'
typestringbrush 类型,可选项:'rect' | 'x-rect' | 'y-rect' | 'cirlce' | 'path' (polygon). 默认: 'rect'
actionstringbrush action, options: 'filter' | 'highlight'. Default: 'filter'
maskMaskCfgConfiguration of mask.
buttonButtonCfgConfiguration of rRset Button,works when action is equal to 'filter'

Types of MaskCfg are as follows:

PropertiesTypeDescription
styleShapeAttrsmask 样式

Types of ButtonCfg are as follows:

export type ButtonCfg = {
  /**
   * padding of button
   */
  padding?: number | number[];
  /**
   * text of button
   */
  text?: string;
  /**
   * custom style of text
   */
  textStyle?: {
    default?: ShapeAttrs;
  };
  /**
   * custom style of button
   */
  buttonStyle?: {
    default?: ShapeAttrs;
    active?: ShapeAttrs;
  };
};

Events

  1. List of vents of brush-filter interaction,
Event NameDescription
G2.BRUSH_FILTER_EVENTS.BEFORE_FILTERHook before brush event to trigger filter append
G2.BRUSH_FILTER_EVENTS.AFTER_FILTERHook after brush event to trigger filter append
G2.BRUSH_FILTER_EVENTS.BEFORE_RESETHook before brush event to trigger filter reset append
G2.BRUSH_FILTER_EVENTS.AFTER_RESETHook after brush event to trigger filter reset append

example:

  1. List of vents of brush-highlight interaction,
Event NameDescription
G2.ELEMENT_RANGE_HIGHLIGHT_EVENTS.BEFORE_HIGHLIGHTHook before event to trigger element-range highlight append
G2.ELEMENT_RANGE_HIGHLIGHT_EVENTS.AFTER_HIGHLIGHTHook after event to trigger element-range highlight append
G2.ELEMENT_RANGE_HIGHLIGHT_EVENTS.BEFORE_CLEARHook before event to trigger element-range-highlight reset append
G2.ELEMENT_RANGE_HIGHLIGHT_EVENTS.AFTER_CLEARHook after event to trigger element-range-highlight reset append

example:

Add interactions

Usage:

// Enable the Active interaction when the mouse moves over a chart element (bar in a bar, dot in a dot, etc.)
interactions: [{ type: 'element-active' }];

// Enable multiple interactions
interactions: [{ type: 'element-active' }, { type: 'brush' }];

Config interactions

通过 cfg 可以对交互行为进行配置,详细参考 G2 | 修改交互的默认交互

// 修改 tooltip 触发事件
interactions: [
  { 
    type: 'tooltip',
    cfg: { start: [{ trigger: 'element:click', action: 'tooltip:show' }] } 
  }
]

Remove the interaction

// 方式1: 关闭 tooltip 交互
interactions: [{ type: 'tooltip', enable: false }]

// 方式2:
plot.chart.removeInteraction('interaction-type');

Example:

// Removes legend filtering interaction
plot.chart.removeInteraction('legend-filter');

Annotations are array types and can be set multiple times.

annotations: [
  {
    type: 'text',
    position: ['median', 'median'],
    content: '辅助文本',
    style: {
      fill: 'red',
    },
  },
];

💠 Text Annotation

type
optional string

需要指定 type: 'text', 标识为:辅助文本,在指定位置添加文本说明。

position
required [string, string] | Datum | ((xScale, yScales) => [string, string])

文本标注位置。

Example

x
optional number

文本标注位置 x,需要搭配 y 属性配置。不建议使用,建议使用 position

y
optional number

文本标注位置 y,需要搭配 x 属性配置。不建议使用,建议使用 position

content
optional string

Text annotations 的文本标注内容。

rotate
optional number

文本的旋转角度,弧度制。顺时针旋转。

offsetX
optional number

文本在 x 轴方向的偏移量。

offsetY
optional number

文本在 y 轴方向的偏移量。

style
optional object

文本标注样式,参考绘图属性

background
optional object

文字包围盒样式设置。

参数名类型描述
styleobject文本背景的样式, 参考绘图属性
paddingnumber | number[]文本背景周围的留白
maxLength
optional number

文文本的最大长度。

autoEllipsis
optional boolean

超出 maxLength 是否自动省略。

ellipsisPosition
optional head | middle | tail

文本截断的位置。

isVertical
optional boolean

文本在二维坐标系的显示位置,是沿着 x 轴显示 还是沿着 y 轴显示。

💠 Line Annotation

type
optional string

需要指定 type: 'line', 标识为:辅助线(可带文本),例如表示平均值或者预期分布的直线。

start
optional AnnotationPosition

起始位置,一般用于 line、region 等。

AnnotationPosition 类型定义如下:

type AnnotationPositionCallback = (
  xScales: Scale[] | Record<string, Scale>,
  yScales: Scale[] | Record<string, Scale>
) => [number | string, number | string];

// types of annotation
type AnnotationPosition =
  | [number | string, number | string]
  | Record<string, number | string>
  | AnnotationPositionCallback;

除了指定原始数据之外,还可以使用预设定数据点,如:

  • 'min': 最小值,minimum value.
  • 'max': 最大值,maximum value.
  • 'mean': 平均值,average value.
  • 'median': 中位值,median value.
  • 'start': 即 0.
  • 'end': 即 1.

Example

end
optional AnnotationPosition

结束位置,一般用于 line、region 等。具体配置属性参考: start

style
optional object

辅助线样式属性,参考绘图属性

text
optional LineAnnotationTextCfg

辅助线上的文本设置。

LineAnnotationTextCfg 类型定义如下:

type LineAnnotationTextCfg = {
  /** 文本内容*/
  content?: string;
  /** 自动旋转,沿着线的方向,默认 true */
  autoRotate?: boolean;
  /** 文本的偏移 x */
  offsetX?: number;
  /** 文本的偏移 y */
  offsetY?: number;
  /** 字体样式,参考绘图属性 */
  style?: object;
};

Example

top
optional boolean

指定 annotation 是否绘制在 canvas 最上层,默认为 false, 即绘制在最下层。

offsetX
optional number

x 轴方向的偏移量。

offsetY
optional number

y 轴方向的偏移量。

animate
optional boolean

是否进行动画。

animateOption
optional object

动画参数配置,当且仅当 animate 属性为 true,即动画开启时生效。,参考动画参数配置

💠 Arc Annotation

type
optional string

需要指定 type: 'arc', 标识为:辅助弧线,只在极坐标系下生效。常用于绘制仪表盘。

start
optional AnnotationPosition

起始位置,一般用于 line、region 等。

AnnotationPosition 类型定义如下:

type AnnotationPositionCallback = (
  xScales: Scale[] | Record<string, Scale>,
  yScales: Scale[] | Record<string, Scale>
) => [number | string, number | string];

// types of annotation
type AnnotationPosition =
  | [number | string, number | string]
  | Record<string, number | string>
  | AnnotationPositionCallback;

除了指定原始数据之外,还可以使用预设定数据点,如:

  • 'min': 最小值,minimum value.
  • 'max': 最大值,maximum value.
  • 'mean': 平均值,average value.
  • 'median': 中位值,median value.
  • 'start': 即 0.
  • 'end': 即 1.

Example

end
optional AnnotationPosition

结束位置,一般用于 line、region 等。具体配置属性参考: start

style
optional object

辅助线样式属性,参考绘图属性

💠 Image Annotation

type
optional string

需要指定 type: 'image', 标识为:辅助图片,在图表上添加辅助图片。

src
optional string

图片路径,用于 image 中。

position
optional [string, string] | Datum | ((xScale, yScales) => [string, string])

图片标注位置。

Example

start
optional AnnotationPosition

起始位置,需搭配 end 使用,也可以直接只使用 position。具体配置属性参考 Line Annotation start 配置。

除了指定原始数据之外,还可以使用预设定数据点,如:

  • 'min': 最小值,minimum value.
  • 'max': 最大值,maximum value.
  • 'mean': 平均值,average value.
  • 'median': 中位值,median value.
  • 'start': 即 0.
  • 'end': 即 1.

Example

end
optional AnnotationPosition

结束位置,需搭配 start 使用,也可以直接只使用 position。具体配置属性参考: start

style
optional object

图片标注样式,可以设置图片标注的宽度和高度,如下:

annnotations: [{
  type: 'image',
  src: 'xxx',
  style: {
    width: 50,
    height: 50,
  }
}]
top
optional boolean

指定 annotation 是否绘制在 canvas 最上层,默认为 false, 即绘制在最下层。

offsetX
optional number

x 轴方向的偏移量。

offsetY
optional number

y 轴方向的偏移量。

animate
optional boolean

是否进行动画。

animateOption
optional object

动画参数配置,当且仅当 animate 属性为 true,即动画开启时生效。,参考动画参数配置

💠 Region Annotation

type
optional string

需要指定 type: 'region', 标识为:辅助框,框选一段图区,设置背景、边框等。

start
optional AnnotationPosition

起始位置,一般用于 line、region 等。

AnnotationPosition 类型定义如下:

type AnnotationPositionCallback = (
  xScales: Scale[] | Record<string, Scale>,
  yScales: Scale[] | Record<string, Scale>
) => [number | string, number | string];

// types of annotation
type AnnotationPosition =
  | [number | string, number | string]
  | Record<string, number | string>
  | AnnotationPositionCallback;

除了指定原始数据之外,还可以使用预设定数据点,如:

  • 'min': 最小值,minimum value.
  • 'max': 最大值,maximum value.
  • 'mean': 平均值,average value.
  • 'median': 中位值,median value.
  • 'start': 即 0.
  • 'end': 即 1.

Example

end
optional AnnotationPosition

结束位置,一般用于 line、region 等。具体配置属性参考: start

style
optional object

辅助线样式属性,参考绘图属性

top
optional boolean

指定 annotation 是否绘制在 canvas 最上层,默认为 false, 即绘制在最下层。

offsetX
optional number

x 轴方向的偏移量。

offsetY
optional number

y 轴方向的偏移量。

animate
optional boolean

是否进行动画。

animateOption
optional object

动画参数配置,当且仅当 animate 属性为 true,即动画开启时生效。,参考动画参数配置

💠 DataMarker Annotation

type
optional string

需要指定 type: 'dataMarker', 标识为:特殊数据点标注,多用于折线图和面积图。

position
required [string, string] | Datum | ((xScale, yScales) => [string, string])

DataMarker 标注位置,参考 Text Annotation 标注的 position 设置。

Example

point
optional null | DataMarkerPointCfg

point 设置。当设置为:null 时,不展示 point 点标识。

DataMarkerPointCfg 类型定义如下:

// 当前只支持对 point 的样式进行设置。
type DataMarkerPointCfg = {
  style?: ShapeAttrs;
}
line
optional null | DataMarkerLineCfg

line 设置。当设置为:null 时,不展示 line 标识。

DataMarkerLineCfg 类型定义如下:

// 当前只支持对 line 的样式以及长度进行设置。
type DataMarkerPointCfg = {
  style?: ShapeAttrs;
  length?: number;
}
text
optional null | AnnotationTextCfg

DataMareker 辅助标记上的文本设置。当设置为:null 时,不展示文本标识。

AnnotationTextCfg 类型定义如下:

// 当前只支持对 line 的样式以及长度进行设置。
type AnnotationTextCfg = {
  /** 文本内容*/
  content?: string;
  /** 自动旋转,沿着线的方向,默认 true */
  autoRotate?: boolean;
  /** 文本的偏移 x */
  offsetX?: number;
  /** 文本的偏移 y */
  offsetY?: number;
  /** 字体样式,参考绘图属性 */
  style?: object;
};
autoAdjust
optional boolean

文本超出绘制区域时,是否自动调节文本方向。

direction
optional upward | downward

朝向。

`markdown:docs/common/annotations/base-annotation.zh.md`

💠 DataRegion Annotation

type
optional string

需要指定 type: 'dataRegion', 标识为:特殊数据区间标注,多用于折线图和面积图。

position
required [string, string] | Datum | ((xScale, yScales) => [string, string])

DataMarker 标注位置,参考 Text Annotation 标注的 position 设置。

Example

lineLength
number optional default: 0

line 长度。

region
null | { style?: ShapeAttrs } optional default: 0

标注区间的配置。点击 ShapeAttrs 查看详细样式配置。

text
null | EnhancedTextCfg optional default: 0

文本的配置。

top
optional boolean

指定 annotation 是否绘制在 canvas 最上层,默认为 false, 即绘制在最下层。

offsetX
optional number

x 轴方向的偏移量。

offsetY
optional number

y 轴方向的偏移量。

animate
optional boolean

是否进行动画。

animateOption
optional object

动画参数配置,当且仅当 animate 属性为 true,即动画开启时生效。,参考动画参数配置

💠 Region Annotation

type
optional string

需要指定 type: 'regionFilter', 标识为:区域着色,将图表中位于矩形选区中的图形元素提取出来,重新着色。

start
optional AnnotationPosition

起始位置,一般用于 line、region 等。

AnnotationPosition 类型定义如下:

type AnnotationPositionCallback = (
  xScales: Scale[] | Record<string, Scale>,
  yScales: Scale[] | Record<string, Scale>
) => [number | string, number | string];

// types of annotation
type AnnotationPosition =
  | [number | string, number | string]
  | Record<string, number | string>
  | AnnotationPositionCallback;

除了指定原始数据之外,还可以使用预设定数据点,如:

  • 'min': 最小值,minimum value.
  • 'max': 最大值,maximum value.
  • 'mean': 平均值,average value.
  • 'median': 中位值,median value.
  • 'start': 即 0.
  • 'end': 即 1.

Example

end
optional AnnotationPosition

结束位置,一般用于 line、region 等。具体配置属性参考: start

style
optional object

辅助线样式属性,参考绘图属性

color
optional string

染色色值,一般用于 regionFilter。

apply
optional string[]

设定 regionFilter 只对特定 geometry 类型起作用,如 apply: ['area'],一般用于 regionFilter。

top
optional boolean

指定 annotation 是否绘制在 canvas 最上层,默认为 false, 即绘制在最下层。

offsetX
optional number

x 轴方向的偏移量。

offsetY
optional number

y 轴方向的偏移量。

animate
optional boolean

是否进行动画。

animateOption
optional object

动画参数配置,当且仅当 animate 属性为 true,即动画开启时生效。,参考动画参数配置

💠 Html Annotation

type
optional string

需要指定 type: 'html',。自定义任意 HTML 类型的图形标记,通过 option 中的 html 配置来在图表中使用 HTML DOM 元素来添加图形标记。option 配置如下:

container
string | HTMLElement optional

可选,自定义 HTML 图形标记的容器元素

html
string | HTMLElement | ((container: HTMLElement, view: View) => void | string | HTMLElement)

自定义的图形标记的 HTML 元素,可为 HTML DOM 字符串,或 HTML 元素,或 html 回调函数

alignX
'left' | 'middle' | 'right' optional default: 'left'

DOM 元素在 X 方向的对齐方式

alignY
'top' | 'middle' | 'bottom' optional default: 'top'

DOM 元素在 Y 方向的对齐方式

offsetX
number optional

X 方向的偏移

offsetY
number optional

Y 方向的偏移

💠 Shape Annotation

type
optional string

需要指定 type: 'shape',。自定义任意类型的图形标记,通过 option 中的 render 回调函数来在图表区域绘制自定义标记。option 配置如下:

render
( container: IGroup, view: View, helpers: { parsePosition: (position: [string | number, string | number] | Datum) => Point } ) => void

自定义标记的绘制 render 函数,其他 container 为标记绘制的父容器, view 为图形实例, helpers 为辅助函数,其他 parserPosition 可以用来计算数据点对应的坐标位置

top
optional boolean

指定 annotation 是否绘制在 canvas 最上层,默认为 false, 即绘制在最下层。

offsetX
optional number

x 轴方向的偏移量。

offsetY
optional number

y 轴方向的偏移量。

animate
optional boolean

是否进行动画。

animateOption
optional object

动画参数配置,当且仅当 animate 属性为 true,即动画开启时生效。,参考动画参数配置