logo

G2

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

wordCloud

Previous
connector
Next
View

Resources

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

Community

Ant Financial Experience Tech
seeconfSEE Conf-Experience Tech Conference

Help

GitHub
StackOverflow

more productsMore Productions

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

Loading...

Overview

wordCloud is a specialized tool for generating word cloud visualizations. Word clouds are a visual representation that intuitively displays the frequency of keywords in text data through words of different sizes, colors, and positions to reflect the importance or weight of words.

When using the wordCloud component, users can easily transform text data into visual word clouds. It supports highly customizable configuration options, including word size ranges, color mapping, rotation angles, and layout algorithms, thereby meeting diverse visualization needs. Additionally, wordCloud can seamlessly integrate with other G2 features, such as data filtering, interactive event binding, etc., further enhancing user experience.

Whether used to display trending topics on social media, analyze user comment sentiment, or present keyword distribution, wordCloud can elegantly help users quickly gain insights into trends and patterns behind the data. wordCloud is not only simple to use but also delivers excellent performance, making it an ideal choice in the field of data visualization.

Getting Started

import { Chart } from '@antv/g2';
const chart = new Chart({
container: 'container',
});
chart.options({
type: 'wordCloud', // Specify chart type as word cloud
data: {
type: 'fetch',
value: 'https://assets.antv.antgroup.com/g2/philosophy-word.json',
},
layout: {
spiral: 'rectangular', // Word cloud layout mode: rectangular spiral layout
},
encode: { color: 'text' }, // Map data field `text` to word cloud color
legend: false,
axis: false,
tooltip: false,
});
chart.render();

For more examples, please visit the Chart Examples - Text page.

Configuration

PropertyDescriptionTypeDefaultRequired
encodeConfigure visual channels for wordCloud mark, including x, y, color, size, etc., to specify relationships between visual element properties and dataencode-✓
labelsConfigure custom node data labels for wordCloudlabel[][]
layoutConfigure wordCloud layout, including padding, rotate, etc.layout-
paddingConfigure margin of wordCloud containernumber0
scaleConfigure graphic scaling for wordCloud mark, including x, y, series, size, etc.scale-
styleConfigure wordCloud graphic stylestyle-

encode

Configure visual channels for wordCloud mark, an important configuration that defines the mapping relationship between data fields and visual properties, determining how data is transformed into visual representation.

PropertyDescriptionTypeDefaultRequired
textBind the text property channel of wordCloud markencode'text'
rotateBind the rotate property channel of wordCloud mark, used to map data fields to font rotation of graphic elementsencode'rotate'
fontSizeBind the fontSize property channel of wordCloud mark, used to map data fields to font size of graphic elementsencode'size'
colorBind the color property channel of wordCloud mark, mapping data fields to color channelencode-

For more encode configurations, please visit the encode introduction page.

scale

scale is used to define how data maps to visual properties (such as color, size, shape, etc.). In the context of cell usage, the common role of scale is to provide mapping rules for each visual channel (such as color, size, position, etc.), enabling data points to be accurately represented.

PropertyDescriptionTypeDefaultRequired
xDefine mapping rules from data fields to X-axis visual positionRecord<string, scale>{ range: [0, 1] }
yDefine mapping rules from data fields to Y-axis visual positionRecord<string, scale>{ range: [0, 1] }

For more scale configurations, please visit the scale introduction page.

padding

Configure margins of wordCloud container, you can configure margins in different directions through padding{Position}

type Position = 'Top' | 'Bottom' | 'left' | 'right';

Comparison with padding configuration in layout

PropertyDescriptionTypeExample
option.paddingConfigure margin of wordCloud containernumber
option.layout.paddingSet spacing between words in pixels, can be a specific value or dynamic functionnumber | (word: any) => number

layout

PropertyDescriptionTypeDefault
fontSet font style, can be string or function, function returns font based on word, modifies d3 word cloud configurationstring | (word: any) => string'Impact'
fontSizeSet font size, can be specific value, range [min, max] or function, modifies d3 word cloud configurationnumber | [number, number] | (word: any) => number-
imageMaskSet image as mask for word layout, can be HTML image element or image path string'HTMLImageElement | string-
onConfigure event listener functions, can listen to layout completion (end) or word update (word)((type: 'end', details?: { cloud; words; bounds }) => void) | ((type: 'word', details?: { cloud; word }) => void)-
paddingSet spacing between words in pixels, can be specific value or dynamic functionnumber | (word: any) => number2
rotateSet rotation angle of words, can be specific value or dynamic functionnumber | word => number() => (~~(Math.random() * 6) - 3) * 30
randomSet random number generator, can be specific value or functionnumber | (word => number)-
sizeSet rectangular width and height of layout, format is [width, height][number, number][20, 60]
spiralSet word arrangement mode, can choose "archimedean" or "rectangular" built-in spiral types, or implement custom through function'archimedean' | 'rectangular'-
textSet word text accessor function, used to return word text based on word data(word: any) => string(d) => d.text
timeIntervalSet time interval of layout algorithm, controls runtimenumber-

spiral

spiral is a parameter that controls the word cloud layout algorithm, determining how words are arranged on the canvas and their path patterns. By adjusting spiral, you can optimize the visual effect, layout density, and performance of the word cloud.

Parameter ValueDescriptionUse Case
archimedeanArchimedean spiral (default), words arrange from center outward in spiral path, more compact layout.General scenarios, pursuing natural compact layout
rectangularRectangular spiral, words arrange in rectangular path, faster computation but relatively sparse layout.Optimizing performance when data volume is large

(() => {
const spiralMap = [
{
label: 'Archimedean Spiral',
spiral: 'archimedean',
},
{
label: 'Rectangular Spiral',
spiral: 'rectangular',
},
];
const chart = new G2.Chart();
chart.options({
type: 'wordCloud',
data: {
type: 'fetch',
value: 'https://assets.antv.antgroup.com/g2/philosophy-word.json',
},
layout: {
spiral: 'rectangular',
},
encode: { color: 'text' },
});
const handleSetSpiral = (spiral) => {
// Set selected coordinate system
chart.options({
layout: { spiral },
});
chart.render(); // Re-render chart
};
// layout-spiral selector
const selectorContainer = document.createElement('div');
selectorContainer.textContent = 'Choose spiral ';
const selector = document.createElement('select');
selector.innerHTML = spiralMap.map(
(spiral, index) =>
`<option value="${spiral.spiral}" ${index === 0 ? 'selected' : ''}>${
spiral.label
}</option>`,
);
selector.onchange = (e) => {
handleSetSpiral(e.target.value);
};
selectorContainer.appendChild(selector);
const node = chart.getContainer();
node.insertBefore(selectorContainer, node.childNodes[0]);
chart.render();
return node;
})();

imageMask

imageMask is a key configuration item for controlling word cloud shape. Its function is to limit the word cloud layout within the contour range of a specified image mask, thereby generating word cloud effects that match the image shape.

imageMask receives a mask image, and the WordCloud layout algorithm analyzes the pixel information of the imageMask image, treating non-transparent areas of the image as areas where words can be placed, while transparent areas prohibit word placement. Words dynamically adjust their size and position within non-transparent areas based on weight (such as word frequency).

Notes:

  • Image quality: Mask images should typically be monochrome (black and white) images. Generally, word clouds define shapes based on non-white areas.
  • Image loading: When using image masks, ensure that image resources are fully loaded, otherwise rendering issues may occur.
  • Performance impact: Complex shapes (such as high-resolution images) may affect word cloud construction speed.

import { Chart } from '@antv/g2';
const chart = new Chart({
container: 'container',
});
chart.options({
type: 'wordCloud',
layout: {
imageMask:
'https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*LKU4TYEiB-4AAAAAAAAAAAAADmJ7AQ/original',
fontSize: 12,
},
data: {
type: 'fetch',
value:
'https://gw.alipayobjects.com/os/antvdemo/assets/data/antv-keywords.json',
},
encode: { color: 'name', text: 'name' },
legend: false,
});
chart.render();

style

Composite graphic marks need to distinguish graphic configurations through different prefixes.

PropertyDescriptionTypeDefault
fontStyleSet text style, calls G drawing for renderingFontStyle | (datum, index, data, column) => FontStyle'normal'
fontSizeSet text font size, calls G drawing for renderingnumber | (datum, index, data, column) => number-
fontWeightSet text font weight, calls G drawing for renderingFontWeight | number | (datum, index, data, column) => number |FontWeight'normal'
fillFill color of graphicnumber | (datum, index, data, column) => string-
fillOpacityFill opacity of graphicnumber | (datum, index, data, column) => number-
strokeStroke of graphicnumber | (datum, index, data, column) => string-
strokeOpacityStroke opacitynumber | (datum, index, data, column) => number-
textText contentnumber | (datum, index, data, column) => string-
textAlignSet text alignmentTextAlign | (datum, index, data, column) => TextAlign'center'
textBaselineSet text baseline positionTextBaseline | (datum, index, data, column) => TextBaseline'middle'
lineWidthWidth of graphic strokenumber | (datum, index, data, column) => number-
lineDashDashed line configuration for stroke, first value is length of each dash segment, second value is distance between segments. Setting lineDash to [0, 0] results in no stroke.[number,number] |(datum, index, data, column) => [number, number]-
opacityOverall opacity of graphicnumber | (datum, index, data, column) => number-
shadowColorShadow color of graphicnumber | (datum, index, data, column) => string-
shadowBlurGaussian blur coefficient of graphic shadownumber | (datum, index, data, column) => number-
shadowOffsetXSet horizontal distance of shadow from graphicnumber | (datum, index, data, column) => number-
shadowOffsetYSet vertical distance of shadow from graphicnumber | (datum, index, data, column) => number-
cursorMouse style. Same as CSS mouse style, default 'default'.number | (datum, index, data, column) => string'default'
type FontStyle = 'normal' | 'italic' | 'oblique';
type FontWeight = 'normal' | 'bold' | 'lighter';
type TextAlign = 'left' | 'center' | 'right';
type TextBaseline = 'top' | 'middle' | 'bottom';

Try it out: