Loading...
Style in G2 is primarily used to control the visual styling of marks, views, and components.
Marks can set their own styles as well as view styles:
({type: 'interval',style: {// Own stylestroke: 'black',strokeWidth: 2,},viewStyle: {// View styleviewFill: 'red',contentFill: 'yellow',},});
// API// First approachchart.interval().style('stroke', 'black').style('strokeWidth', 2).viewStyle('viewFill', 'red').viewStyle('contentFill', 'yellow');// Second approachchart.interval().style({stroke: 'black',strokeWidth: 2,}).viewStyle({viewFill: 'red',contentFill: 'yellow',});
Views can set their own styles:
({type: 'view',style: {viewFill: 'red',contentFill: 'yellow',},});
// API// First approachchart.style('viewFill', 'red').style('contentFill', 'yellow');// Second approachchart.style({viewFill: 'red',contentFill: 'yellow',});
All chart components can also set styles, for example legends:
({type: 'interval',legend: {color: {// Legend item marker styles (categorical legend)itemMarkerFill: '#5B8FF9',itemMarkerStroke: '#333',itemMarkerStrokeOpacity: 0.8,// Legend item label styles (categorical legend)itemLabelFontSize: 12,itemLabelFill: '#666',itemLabelFontFamily: 'sans-serif',},},});
In addition to setting visual properties through mark.encode
, they can also be set through mark.style
. The main differences between the two are:
mark.encode
are special - either unique to the mark (like the src
channel for images) or have special logic (like the x
channel affecting x-axis generation).mark.encode
tends to set data-related channels, while mark.style
tends to set data-independent channels. However, mark.style
also supports callbacks for data-driven channels.For the shape
property, it can be configured through either encode.shape
or style.shape
. The difference is:
Configure through encode.shape
(Recommended):
style.shape
settingsConfigure through style.shape
:
encode.shape
is not setConfigure hollow bar chart:
// Method 1: Through encode.shapechart.options({type: 'interval',encode: {x: 'category',y: 'value',shape: 'hollow', // Configure as hollow rectangle},});// Method 2: Through style.shapechart.options({type: 'interval',encode: {x: 'category',y: 'value',},style: {shape: 'hollow', // Configure as hollow rectangle},});
Shape types supported by different marks:
rect
(solid rectangle), hollow
(hollow rectangle), funnel
(funnel shape), pyramid
(pyramid shape)hollow
(hollow circle), point
(solid circle), hollowSquare
(hollow square), etc.rect
(solid rectangle), hollow
(hollow rectangle)line
(straight line), smooth
(smooth curve), vh
(step line, vertical then horizontal connection), etc.Here's a complete example of a hollow bar chart:
import { Chart } from '@antv/g2';const chart = new Chart({container: 'container',});chart.options({type: 'interval',data: [{ genre: 'Sports', sold: 275 },{ genre: 'Strategy', sold: 115 },{ genre: 'Action', sold: 120 },{ genre: 'Shooter', sold: 350 },{ genre: 'Other', sold: 150 },],encode: {x: 'genre',y: 'sold',shape: 'hollow', // Configure as hollow rectangle},style: {stroke: '#1890ff', // Set stroke colorstrokeWidth: 2, // Set stroke width},});chart.render();
You can also achieve the same effect through style.shape
configuration:
import { Chart } from '@antv/g2';const chart = new Chart({container: 'container',});chart.options({type: 'interval',data: [{ genre: 'Sports', sold: 275 },{ genre: 'Strategy', sold: 115 },{ genre: 'Action', sold: 120 },{ genre: 'Shooter', sold: 350 },{ genre: 'Other', sold: 150 },],encode: {x: 'genre',y: 'sold',},style: {shape: 'hollow', // Configure as hollow rectangle through stylestroke: '#52c41a', // Set stroke colorstrokeWidth: 2, // Set stroke width},});chart.render();
Styles for different areas can be set using the ${name}${Style}
format, where Style
represents all styles supported by G's rectangle, such as fill
, stroke
, etc. Note that the first letter should be capitalized to form camelCase.
For example, coloring different areas in the chart below:
import { Chart } from '@antv/g2';const chart = new Chart({container: 'container',});chart.options({type: 'view',height: 280,inset: 10,marginTop: 30,marginLeft: 40,marginBottom: 10,marginRight: 20,style: {// Set view stylesviewFill: '#4e79a7',plotFill: '#f28e2c',mainFill: '#e15759',contentFill: '#76b7b2',},children: [{type: 'point',data: {type: 'fetch',value: 'https://assets.antv.antgroup.com/g2/commits.json',},encode: {x: (d) => new Date(d.time).getUTCHours(),y: (d) => new Date(d.time).getUTCDay(),size: 'count',shape: 'point',},transform: [{ type: 'group', size: 'sum' }, { type: 'sortY' }],scale: { y: { type: 'point' } },style: { shape: 'point', fill: '#59a14f' },axis: {x: { title: 'time (hours)', tickCount: 24 },y: { title: 'time (day)', grid: true },},legend: false,},],});chart.render();
Component styles refer to the visual styling configurations for various chart components such as axes, legends, labels, titles, etc. Each component provides rich styling configuration options, supporting fine-grained style control over component sub-elements.
Axes consist of multiple elements including title, axis line, ticks, tick labels, and grid lines, each of which can be styled independently:
({type: 'interval',axis: {x: {// Title stylestitle: 'X Axis Title',titleFontSize: 16,titleFontFamily: 'Arial',titleFontWeight: 'bold',titleFill: '#333',// Axis line stylesline: true,lineStroke: '#666',lineLineWidth: 2,// Tick stylestick: true,tickStroke: '#999',tickLineWidth: 1,// Tick label styleslabelFontSize: 12,labelFill: '#666',labelFontFamily: 'sans-serif',// Grid line stylesgrid: true,gridStroke: '#e6e6e6',gridStrokeOpacity: 0.7,},y: {// Y-axis style configuration similar...},},});
For more configuration on axis styles, see Axis.
Legends support both categorical and continuous legend types, both offering rich styling properties:
({type: 'interval',legend: {color: {// Title stylestitle: 'Legend Title',titleFontSize: 14,titleFontFamily: 'Arial',titleFill: '#333',titleFontWeight: 'bold',// Legend item marker styles (categorical legend)itemMarkerFill: '#5B8FF9',itemMarkerStroke: '#333',itemMarkerStrokeOpacity: 0.8,// Legend item label styles (categorical legend)itemLabelFontSize: 12,itemLabelFill: '#666',itemLabelFontFamily: 'sans-serif',// Continuous legend stylesribbon: {fill: '#5B8FF9',stroke: '#333',},},},});
For more configuration on legend styles, see Legend.
Data labels support rich text styling configurations:
({type: 'interval',labels: [{text: 'value',style: {fontSize: 12,fontFamily: 'Arial',fontWeight: 'normal',fill: '#333',stroke: '#fff',strokeOpacity: 0.8,textAlign: 'center',textBaseline: 'middle',shadowColor: 'rgba(0,0,0,0.3)',shadowBlur: 3,dx: 0,dy: -10,},},],});
For more configuration on label styles, see Label.
Chart titles include both main title and subtitle, both supporting detailed style configuration:
({type: 'interval',title: {// Main titletitle: 'Chart Main Title',titleFontSize: 20,titleFontFamily: 'Arial',titleFontWeight: 'bold',titleFill: '#333',titleStroke: '#000',titleLineWidth: 1,// Subtitlesubtitle: 'Chart Subtitle',subtitleFontSize: 14,subtitleFontFamily: 'Arial',subtitleFontWeight: 'normal',subtitleFill: '#666',// Layout configurationalign: 'center',spacing: 8,},});
For more configuration on title styles, see Title.
Tooltip styles are mainly customized through interaction configuration, supporting CSS styles, marker styles, and crosshair styles:
({type: 'interval',tooltip: {title: 'name',items: ['value'],},interaction: {tooltip: {// CSS style configurationcss: {'.g2-tooltip': {background: 'rgba(0,0,0,0.8)',color: '#fff','font-size': '12px',padding: '8px 12px','border-radius': '4px',border: '1px solid #ccc',},'.g2-tooltip-title': {'font-weight': 'bold','font-size': '14px',},'.g2-tooltip-list-item-value': {'font-weight': 'normal',},},// Marker stylesmarker: true,markerFill: '#5B8FF9',markerStroke: '#fff',markerLineWidth: 2,// Crosshair stylescrosshairs: true,crosshairsStroke: '#999',crosshairsLineDash: [4, 4],},},});
For more configuration on tooltip styles, see Tooltip.
All component style configurations follow the same naming conventions:
fontSize
, fontFamily
, fontWeight
, fill
, stroke
, etc.shadowColor
, shadowBlur
, shadowOffsetX
, shadowOffsetY
opacity
, fillOpacity
, strokeOpacity
dx
, dy
cursor
This unified naming convention provides a consistent experience when configuring styles across different components.
G2 uses G as its drawing engine. Style configurations for various graphics, such as line.style
for line charts and interval.style
for bar charts, as well as some component style configurations like label.style
and axis.line${style}
, are directly passed through to G's drawing properties.
For user convenience, here's a brief introduction to commonly used drawing properties in G2:
Property | Description | Type | Default | Required |
---|---|---|---|---|
fill | Fill color of the graphic | string | ||
fillOpacity | Fill transparency of the graphic | number | ||
stroke | Stroke color of the graphic | string | ||
strokeOpacity | Stroke transparency of the graphic | number | ||
lineWidth | Width of the graphic's stroke | number | ||
lineDash | Dashed stroke configuration. First value is the length of each dash, second is the gap. [0,0] means no stroke. | [number,number] | ||
opacity | Overall transparency of the graphic | number | ||
shadowColor | Shadow color of the graphic | string | ||
shadowBlur | Gaussian blur coefficient for the graphic's shadow | number | ||
shadowOffsetX | Horizontal distance of shadow from the graphic | number | ||
shadowOffsetY | Vertical distance of shadow from the graphic | number | ||
cursor | Mouse cursor style. Same as CSS cursor | string | default |
Try using the full range of graphic style properties to configure the interval
graphic style of a basic bar chart in the code editor below:
import { Chart } from '@antv/g2';const chart = new Chart({ container: 'container', height: 350 });chart.options({type: 'interval',data: [{ genre: 'Sports', sold: 30 },{ genre: 'Strategy', sold: 115 },{ genre: 'Action', sold: 120 },{ genre: 'Shooter', sold: 350 },{ genre: 'Other', sold: 150 },],encode: { x: 'genre', y: 'sold' },style: {fill: 'skyblue',fillOpacity: 0.5,stroke: 'black',lineWidth: 1,lineDash: [4, 5],strokeOpacity: 0.7,opacity: 0.9,shadowColor: 'black',shadowBlur: 10,shadowOffsetX: 5,shadowOffsetY: 5,cursor: 'pointer',},});chart.render();
Property | Description | Type | Default | Required |
---|---|---|---|---|
stroke | Line color | string | ||
strokeOpacity | Line transparency | number | ||
lineWidth | Line width | number | ||
lineDash | Dashed line configuration. First value is dash length, second is gap length. [0,0] means no stroke. | [number,number] | ||
opacity | Overall transparency | number | ||
shadowColor | Shadow color | string | ||
shadowBlur | Gaussian blur coefficient | number | ||
shadowOffsetX | Horizontal distance of shadow from the graphic | number | ||
shadowOffsetY | Vertical distance of shadow from the graphic | number | ||
cursor | Mouse cursor style. Same as CSS cursor | string | default |
Try using the full range of line style properties to configure the line
style of a basic line chart in the code editor below:
import { Chart } from '@antv/g2';const chart = new Chart({ container: 'container', height: 350 });chart.options({type: 'line',data: [{ year: '1991', value: 3 },{ year: '1992', value: 4 },{ year: '1993', value: 3.5 },{ year: '1994', value: 5 },{ year: '1995', value: 4.9 },{ year: '1996', value: 6 },{ year: '1997', value: 7 },{ year: '1998', value: 9 },{ year: '1999', value: 13 },],encode: { x: 'year', y: 'value' },scale: { x: { range: [0, 1] }, y: { domainMin: 0, nice: true } },style: {stroke: 'skyblue',strokeOpacity: 0.9,lineWidth: 4,lineDash: [4, 8],opacity: 0.9,shadowColor: '#d3d3d3',shadowBlur: 10,shadowOffsetX: 10,shadowOffsetY: 10,cursor: 'pointer',},});chart.render();
Similarly, we can configure axis grid lines in the same way:
import { Chart } from '@antv/g2';const chart = new Chart({container: 'container',});chart.options({type: 'line',data: [{ year: '1991', value: 3 },{ year: '1992', value: 4 },{ year: '1993', value: 3.5 },{ year: '1994', value: 5 },{ year: '1995', value: 4.9 },{ year: '1996', value: 6 },{ year: '1997', value: 7 },{ year: '1998', value: 9 },{ year: '1999', value: 13 },],encode: { x: 'year', y: 'value' },scale: { x: { range: [0, 1] }, y: { domainMin: 0, nice: true } },axis: {y: {grid: true,gridStroke: 'red',gridStrokeOpacity: 0.5,gridLineWidth: 2,gridLineDash: [2, 4],},},});chart.render();
Property | Description | Type | Default | Required |
---|---|---|---|---|
fontSize | Font size | number | ||
fontFamily | Font family | string | ||
fontWeight | Font weight | number | ||
lineHeight | Line height of text | number | ||
textAlign | Text alignment | center | end | left | right | start | start | |
textBaseline | Text baseline when drawing text | top | middle | bottom | alphabetic | hanging | bottom | |
fill | Text fill color | string | ||
fillOpacity | Text fill transparency | number | ||
stroke | Text stroke color | string | ||
lineWidth | Text stroke width | number | ||
lineDash | Dashed stroke configuration. First value is dash length, second is gap length. [0,0] means no stroke. | [number,number] | ||
strokeOpacity | Stroke transparency | number | ||
opacity | Overall text transparency | number | ||
shadowColor | Text shadow color | string | ||
shadowBlur | Gaussian blur coefficient for text shadow | number | ||
shadowOffsetX | Horizontal distance of shadow from text | number | ||
shadowOffsetY | Vertical distance of shadow from text | number | ||
cursor | Mouse cursor style. Same as CSS cursor | string | default | |
dx | Horizontal offset of text | number | 0 | |
dy | Vertical offset of text | number | 0 |
Try using the full range of text style properties to configure the center text style of a liquid chart in the code editor below:
import { Chart } from '@antv/g2';const chart = new Chart({container: 'container',height: 350,});chart.options({type: 'liquid',autoFit: true,data: 0.581,style: {waveLength: 50,contentText: 'center text',outlineBorder: 4,outlineDistance: 8,// Drawing propertiescontentFontSize: 30,contentFontFamily: 'sans-serif',contentFontWeight: 500,contentLineHeight: 20,contentTextAlign: 'center',contentTextBaseline: 'middle',contentFill: '#fff',contentFillOpacity: 0.9,contentStroke: 'yellow',contentStrokeOpacity: 0.9,contentLineWidth: 2,contentLineDash: [4, 8],contentOpacity: 1,contentShadowColor: '#d3d3d3',contentShadowBlur: 10,contentShadowOffsetX: 10,contentShadowOffsetY: 10,contentCursor: 'pointer',contentDx: 10,contentDy: 10,},});chart.render();
Similarly, we can configure title text styles in the same way:
import { Chart } from '@antv/g2';const chart = new Chart({container: 'container',});chart.options({type: 'line',data: [{ year: '1991', value: 3 },{ year: '1992', value: 4 },{ year: '1993', value: 3.5 },{ year: '1994', value: 5 },{ year: '1995', value: 4.9 },{ year: '1996', value: 6 },{ year: '1997', value: 7 },{ year: '1998', value: 9 },{ year: '1999', value: 13 },],encode: { x: 'year', y: 'value' },scale: { x: { range: [0, 1] }, y: { domainMin: 0, nice: true } },title: {size: 30,title: "I am a title",align: 'center',spacing: 4,// Drawing propertiestitleFontSize: 30,titleFontFamily: 'sans-serif',titleFontWeight: 500,titleLineHeight: 30,titleTextAlign: 'center',titleTextBaseline: 'middle',titleFill: '#fff',titleFillOpacity: 0.9,titleStroke: 'yellow',titleStrokeOpacity: 0.9,titleLineWidth: 1,titleLineDash: [1, 2],titleOpacity: 1,titleShadowColor: '#d3d3d3',titleShadowBlur: 10,titleShadowOffsetX: 10,titleShadowOffsetY: 10,titleCursor: 'pointer',titleDx: 10,titleDy: 10,},});chart.render();
Note:
l
indicates linear gradient usage. Green text represents variables that users can customize.
// Using gradient stroke, gradient angle 0, starting color #ffffff, midpoint color #7ec2f3, ending color #1890ffstroke: 'l(0) 0:#ffffff 0.5:#7ec2f3 1:#1890ff';// The following syntax is also supportedstroke: 'linear-gradient(270deg, #ffffff 0%, #7ec2f3 50%, #1890ff 100%)';
Try configuring the fill color of an area chart as a linear gradient in the code editor below:
/*** A recreation of this demo: https://vega.github.io/vega-lite/examples/area_gradient.html*/import { Chart } from '@antv/g2';const chart = new Chart({container: 'container',height: 350,});chart.options({type: 'view',autoFit: true,data: {type: 'fetch',value: 'https://assets.antv.antgroup.com/g2/stocks.json',transform: [{ type: 'filter', callback: (d) => d.symbol === 'GOOG' }],},children: [{type: 'area',encode: { x: (d) => new Date(d.date), y: 'price' },style: { fill: 'l(270) 0:#ffffff 0.5:#7ec2f3 1:#1890ff' },// style: { fill: "linear-gradient(270deg, #ffffff 0%, #7ec2f3 50%, #1890ff 100%)" },},],});chart.render();
You can also create a gradient gauge by configuring the color
channel scale in the code editor below:
import { Chart } from '@antv/g2';const chart = new Chart({container: 'container',height: 350,});chart.options({type: 'gauge',data: {value: { target: 159, total: 400, name: 'score', thresholds: [200, 400] },},scale: {color: { range: ['l(0):0:#37b38e 1:#D9C652', 'l(0):0:#D9C652 1:#f96e3e'] },},style: {textContent: (target, total) => `Score: ${target}Ratio: ${(target / total) * 100}%`,},legend: false,});chart.render();
Note:
r
indicates radial gradient usage. Green text represents variables that users can customize. The x, y, r values of the starting circle are all relative values in the 0-1 range.
// Using gradient fill, gradient starting circle center at the bounding box center of the filled object, radius 0.1 times (bounding box diagonal length / 2), starting color #ffffff, ending color #1890fffill: 'r(0.5, 0.5, 0.1) 0:#ffffff 1:#1890ff';
Try configuring the fill color of a bar chart as a radial gradient in the code editor below:
import { Chart } from '@antv/g2';const chart = new Chart({ container: 'container', height: 350 });chart.options({type: 'interval',height: 350,data: [{ genre: 'Sports', sold: 30 },{ genre: 'Strategy', sold: 115 },{ genre: 'Action', sold: 120 },{ genre: 'Shooter', sold: 350 },{ genre: 'Other', sold: 150 },],encode: { x: 'genre', y: 'sold' },style: {fill: 'r(0.5, 0.5, 0.1) 0:#ffffff 1:#1890ff',},});chart.render();
Fill graphics with specific patterns. Pattern content can be images or Data URLs.
Note:
p
indicates pattern usage. Green text represents variables that users can customize.
a
: The pattern repeats in both horizontal and vertical directionsx
: The pattern repeats only horizontallyy
: The pattern repeats only verticallyn
: The pattern displays only once (no repeat)style: {fill: 'p(a)https://gw.alipayobjects.com/mdn/rms_d314dd/afts/img/A*58XjQY1tO7gAAAAAAAAAAABkARQnAQ',}
Try configuring the fill color of a bar chart as a pattern in the code editor below:
import { Chart } from '@antv/g2';const chart = new Chart({ container: 'container', height: 350 });chart.options({type: 'interval',height: 350,data: [{ genre: 'Sports', sold: 30 },{ genre: 'Strategy', sold: 115 },{ genre: 'Action', sold: 120 },{ genre: 'Shooter', sold: 350 },{ genre: 'Other', sold: 150 },],encode: { x: 'genre', y: 'sold' },style: {fill: 'p(a)https://gw.alipayobjects.com/mdn/rms_d314dd/afts/img/A*58XjQY1tO7gAAAAAAAAAAABkARQnAQ',},});chart.render();
In addition, G2 provides multiple ways to set patterns including built-in patterns
and G API custom patterns
. For details, see Setting Patterns.