G2Plot Documentation

repository·master·Indexed 25 days ago

https://github.com/antvis/g2plot

An interactive and responsive high-level statistical charting library built on top of G2 4.x. G2Plot provides out-of-the-box, enterprise-level charts including Bar, Facet, and Mix plots. It supports multi-layer chart configurations via views and plots, as well as advanced layout options for partitioned datasets.

Tokens
117.1K
Snippets
234
Records
765
Agent score
81%

What's inside G2Plot

  1. Introduction to Facet plots

    master

    Facet plots use G2's recursive view nesting capability to split a dataset into multiple subsets based on specific dimensions. Each subset is then rendered into a pane within a chart matrix. This is a powerful tool for exploratory data analysis to compare patterns across different data subsets.

    Supported facet types include:

    Facet TypeDescription
    rectDefault type. Uses 2 dimensions to form a row/column matrix.
    listUses 1 dimension. You can specify the number of columns per row; extra items wrap automatically.
    circleUses 1 dimension to distribute charts along a circular layout.
    treeUses multiple dimensions, where each dimension acts as a level in a tree structure to expand multi-layer charts.
    mirrorUses 1 dimension to create mirrored charts.
    matrixUses 1 dimension to form a matrix facet.
  2. Develop a custom chart

    master

    To create a new custom chart that can be used within G2Plot or published as an NPM package, follow these three steps:

    1. Define chart default configuration: Establish the standard options for your chart.
    2. Custom adaptor: Implement an adaptor that transforms your configuration into G2 API calls.
    3. Integration: Use the resulting chart in G2Plot or publish it as an NPM package.
  3. Add interactions to a plot

    master

    You can add interactive behaviors to a G2Plot chart by providing an array of interaction objects to the interactions configuration property. Each object must specify a type.

    Common interaction types include:

    • element-active: Enables active state (e.g., highlighting) when the mouse moves over a chart element like a bar or dot.
    • brush: Enables area selection/brushing.
    • tooltip: Enables tooltip displays.
    // Enable the Active interaction when the mouse moves over a chart element
    interactions: [{ type: 'element-active' }];
    
    // Enable multiple interactions
    interactions: [{ type: 'element-active' }, { type: 'brush' }];
  4. Set pattern styles for geometries

    master

    You can apply pattern styles to geometries in G2Plot to override standard styles (like pieStyle or columnStyle). Patterns can be applied uniformly to all geometries or dynamically using a callback function based on the data.

    Patterns support three types:

    • dot
    • line
    • square

    PatternAttr can be a CanvasPattern, a PatternOption object, or a callback function: (datum: Datum, color: string) => PatternOption | CanvasPattern.

    // 1. Set a uniform pattern style for all geometries
    {
       pattern: {
        type: 'dot',
        cfg: {
          size: 4,
          padding: 4,
          rotation: 0,
          fill: '#FFF',
          isStagger: true,
        },
      },
    }
    
    // 2. Set a pattern for each geometry using a callback
    {
      pattern: ({type}, color) => {
        if(type === '分类一') {
          return {
            type: 'dot',
            cfg: {
              backgroundColor: color, // inherit color
            }
          }
        } else if(type === '分类二') {
          return {
             type: 'square',
             cfg: {
               backgroundColor: 'pink', // custom color
             }
           }
        } else if(type === '分类三') {
          return { 
            type: 'line' 
          }
        }
      },
    }
  5. Configure interaction behavior via cfg

    master

    You can customize the behavior of an interaction using the cfg property within the interaction object. For example, you can modify the trigger event for a tooltip interaction.

    // Modify tooltip trigger event
    interactions: [
      {
        type: 'tooltip',
        cfg: { start: [{ trigger: 'element:click', action: 'tooltip:show' }] }
      }
    ]
  6. Design guidelines for Area charts

    master

    Area charts are used to display continuous data to represent trends, accumulation, reduction, and changes.

    When to use:

    • Area Chart: Best for showing trends and changes in continuous data.
    • Stacked Area Chart: Best for showing the relationship between parts and a whole (proportions) rather than conveying specific individual values.

    Data Requirements:

    • Suitable Data: Two continuous fields.
    • Function: Observing data trends.
    • Mapping: Two continuous fields mapped to the X-axis and Y-axis respectively.
    • Data Volume: Recommended for more than two data points/lines.
  7. Quick start with Column plot

    master

    To create a basic Column plot, import the Column class from @antv/g2plot, provide a container ID, and specify the data, xField (categorical dimension), and yField (numerical dimension) in the configuration object. Call .render() to display the chart.

    import { Column } from '@antv/g2plot';
    
    fetch('https://gw.alipayobjects.com/os/antfincdn/K0kfOzo4j%24/column.json')
       .then(data => data.json())
       .then(data => {
          const columnPlot = new Column('container', {
            data,
            xField: 'type',
            yField: 'sales',
          });
    
          columnPlot.render();
       });
  8. Quick Start with Liquid Plot

    master

    The Liquid Plot (also known as Water Wave or Progress Ball) uses a spherical container and the position of a horizontal line within it to represent progress. It requires a single numeric field to function.

    To use it, import Liquid from @antv/g2plot and provide a percent value (a number between 0 and 1) in the configuration object.

    import { Liquid } from '@antv/g2plot';
    
    const liquidPlot = new Liquid('container', {
      percent: 0.25,
    });
    liquidPlot.render();
  9. Design guidelines for Pie and Donut charts

    master

    When to use

    Pie charts use the area, arc, and color of sectors to represent data categories and their proportions. They are best for showing the relationship between parts and a whole, where the sum of all parts equals 100%.

    Data Requirements

    • Suitable Data: Requires one "categorical dimension field" and one "numerical measure field".
    • Function: Comparing the numerical values of different categories.
    • Mapping: The "dimension field" maps to block color and count; the "measure field" maps to block arc length and area.
    • Data Volume: It is recommended to have no more than 9 categories. For more categories, consider grouping them into an "Other" category.

    Usage Recommendations

    • Donut vs. Pie: Donut charts are generally preferred over standard Pie charts for better visual clarity.
    • Center Indicators: For Donut charts, it is recommended to use composite indicators (e.g., total values or key metrics) displayed in the center hole.

    Chart Elements

    • Elements: Pie charts consist of sectors; Donut charts consist of ring segments.
    • Labels: Used to display the percentage (%), category name, and actual numerical value.
    • Composite Indicators: Displayed in the center of a Donut chart or as an indicator card on a portion of the chart.
    • Info Components: Support for legends, tooltips, and indicator cards.
  10. Configure interaction settings via `cfg`

    master

    To customize the behavior of an interaction, use the cfg property within the interaction object. For example, you can change the trigger event for a tooltip interaction from the default to a click event.

    // Modify the tooltip trigger event
    interactions: [
      { 
        type: 'tooltip',
        cfg: { start: [{ trigger: 'element:click', action: 'tooltip:show' }] } 
      }
    ]