Bullet

3 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:[{title: '满意度', ranges: [50,100], measures: [80], target: 85}]

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.

measureField

required string

Use the length of the data bar, the setting field for the actual value, to represent the actual value.

rangeField

required string

Use the setting field for the length of the background bar to represent the range.

targetField

required string

Use a setting field for the position of the scale axis of the measurement mark to represent the target value.

xField

optional string

Used to distinguish different types, suitable for grouping bullet diagrams.

Geometry Style

layout

optional 'horizontal' | 'vertical' default: 'horizontal'

Represents the direction of the bullet diagram.

color

optional object

Set color property of each graph of bullet map.

PropertiesTypeDescriptionDefault
rangestring|string[]Interval background color-
measurestring|string[]Actual value color-
targetstring|string[]Target value color-

size

optional object

Set the size property of each graph of bullet map.

PropertiesTypeDescriptionDefault
rangeSizeAttrInterval Background Style30
measureSizeAttrActual value style20
targetSizeAttrTarget value styles20
type SizeAttr = number | [number, number] | ((datum: Datum) => number);

bulletStyle

optional object

Set the style properties of each bullet map.

PropertiesTypeDescriptionDefault
rangeStyleAttrInterval Background Style{ fillOpacity: 0.5 }
measureStyleAttrActual value style-
targetStyleAttrTarget value styles-
type StyleAttr = ShapeStyle | ((datum: object) => ShapeStyle);

ShapeStyle The structure can be referred to:

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.

Plot Components

label

optional object

Set the label attribute of each graph of the bullet map.

PropertiesTypeDescriptionDefault
rangeGeometryLabelAttrThe label attribute of the range-
measureGeometryLabelAttrThe label attribute of the actual valuetrue
targetGeometryLabelAttrThe label attribute of the target value-
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
    }
  }
}

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>`;
    };
  }
}

axis

Same for xAxis and yAxis.

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

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

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