F2 Documentation

repository·master·Indexed 27 days ago

https://github.com/antvis/f2

A mobile-first, out-of-the-box visualization solution based on the grammar of graphics theory. Designed for H5 environments, F2 is compatible with Node.js, React Native, Weex, and Alipay/WeChat Mini-programs. It supports over 50 chart types and includes specialized packages such as @antv/f2-react for React integration, @antv/f2-algorithm for data sampling (including LTTB and rate sampling), and @antv/f2-wordcloud for word cloud visualizations.

Tokens
70.4K
Snippets
195
Records
355
Agent score
93%

What's inside F2

  1. Overview of F2 Features

    master

    F2 is an HTML5 Canvas-based charting library designed specifically for mobile environments.

    Key capabilities include:

    • Mobile Optimization: Designed for natural interactions and high performance on mobile devices.
    • Multi-Runtime Support: Compatible with H5, Node.js, Weex, React Native, Alipay Mini Programs, and WeChat Mini Programs.
    • Rich Chart Types: Supports 50+ chart types (line, column/bar, pie, scatter, gauges, etc.) based on the grammar of graphics.
    • Extensibility: Flexible mechanisms for customizing shapes, animations, interactions, and styling.
    • Built-in Components: Includes Tooltip, Legend, and Guide components.
  2. Understand F2 Chart Structure and Components

    master

    F2 uses a declarative, component-based architecture. A complete chart is composed of a hierarchy of components:

    • Canvas: The root container providing the rendering environment.
    • Chart: The core engine responsible for data processing and coordinate transformation.
    • Axis: Represents the x or y axes (or angle/radius in polar coordinates).
    • Geometry: The visual representation of data (points, lines, bars, etc.).
    • Tooltip: Displays data information on mouse hover.
    • Legend: Helps users identify data types and ranges.
    • Guide: Used for drawing auxiliary lines, boxes, or text (e.g., warning lines).
  3. F2 Core Features

    master

    F2 is a mobile-first charting library with the following key capabilities:

    • Grammar of Graphics: Supports 50+ chart types (line, column/bar, pie, scatter, gauges, etc.).
    • Mobile Optimized: Small package size (approx. 44k after gzip for non-interactive versions) and high rendering performance.
    • Interactive Components: Built-in support for Tooltip, Legend, and Guide.
    • Extensibility: Flexible mechanisms for customizing shapes, animations, interactions, and styling.
  4. Understand F2 Chart Grammar

    master

    F2 is based on the 'Grammar of Graphics', meaning there are no predefined chart types. Instead, all charts are constructed by combining core graphic grammar elements in a bottom-up manner. The hierarchy of elements is:

    1. Data: The raw input.
    2. Scale: Converts data values to visual spaces.
    3. Geometry + Attribute: The visual marks (points, lines) and their properties.
    4. Coordinate: The mapping of data to a plane (e.g., Cartesian or Polar).
    5. Auxiliary Elements: Enhancements like Axes, Legends, and Tooltips.
  5. Understand the F2 Grammar of Graphics

    master

    F2 is based on 'The Grammar of Graphics', meaning there are no fixed 'chart types'. Instead, all charts are constructed by combining core grammar elements in a bottom-up approach.

    The hierarchy of elements is:

    1. Data: The foundation.
    2. Scale: Transforms data space to attribute space.
    3. Geometry + Attribute: The visual marks and their properties.
    4. Coordinate: Maps marks to a plane.
    5. Auxiliary Elements: Axis, Legend, Tooltip, and Guide.
  6. Understand Geometry components in F2

    master

    Geometry components are the visual elements in F2 charts responsible for mapping data to specific graphical shapes (lines, points, intervals, etc.). All specific geometry components inherit from the Geometry base class, ensuring a consistent API across different chart types.

    Supported Geometry components include:

    • Line: Line charts, curve charts, step charts.
    • Interval: Bar charts, histograms, pie charts, ring charts, funnel charts.
    • Point: Scatter plots, bubble charts.
    • Area: Area charts, stacked area charts.
    • Candlestick: K-line charts, stock charts.
  7. Create a custom View using the withXXX HOC pattern

    master

    F2 encapsulates components using Higher-Order Components (HOC) following a withXXX pattern. To create a custom version of a component (e.g., Legend), you should define a custom View component (e.g., LegendView) and then wrap it using the corresponding HOC (e.g., withLegend).

    In your custom View component, you receive props containing the processed data/logic results. You can also access the component's public functions through these props.

    import { Canvas, Chart, withLegend } from '@antv/f2';
    
    // 1. Define your custom View component
    const CustomLegendView = (props) => {
      const { items } = props;
      return (
        <group style={{ flexDirection: 'row' }}>
          {items.map((item) => {
            const { name, color } = item;
            return (
              <text
                style={{
                  text: name,
                  fill: color,
                }}
              />
            );
          })}
        </group>
      );
    };
    
    // 2. Wrap it with the HOC to create the final component
    const Legend = withLegend(CustomLegendView);
    
    // 3. Use it within the Chart
    <Canvas context={context}>
      <Chart data={data}>
        <Legend position="top" />
      </Chart>
    </Canvas>
  8. Use the Gauge component

    master

    The Gauge component is used to visualize progress or completion levels, commonly for displaying Key Performance Indicators (KPIs). It can show single metric progress, comparisons between target and actual values, or percentage/ratio data.

    import { Canvas, Gauge } from '@antv/f2';
    
    const data = { percent: 0.75 };
    
    <Canvas context={context} pixelRatio={window.devicePixelRatio}>
      <Gauge
        center={{ x: 150, y: 150 }}
        startAngle={Math.PI}
        endAngle={Math.PI * 2}
        percent={0.75}
        r="100px"
      />
    </Canvas>
  9. Configure JSX compilation for Vite

    master

    If you are using Vite, you need to configure @rollup/plugin-babel to handle JSX with the @antv/f2 import source.

    1. Install the required dependencies:
    npm install @rollup/plugin-babel --save-dev
    npm install @babel/plugin-transform-react-jsx --save-dev
    1. Update your vite.config.js as follows:
    import vue from '@vitejs/plugin-vue';
    import vueJsx from '@vitejs/plugin-vue-jsx';
    import { babel } from '@rollup/plugin-babel';
    
    export default defineConfig({
      plugins: [
        babel({
          plugins: [
            [
              '@babel/plugin-transform-react-jsx',
              {
                runtime: 'automatic',
                importSource: '@antv/f2',
              },
            ],
          ],
        }),
        vue(),
        vueJsx(),
      ],
    });
  10. Use the Interval geometry to draw bar, pie, and funnel charts

    master

    The Interval geometry is used to render area-based charts such as bar charts, histograms, Nightingale rose charts, pie charts, donut charts, and funnel charts. It inherits from the Geometry base class.

    To use it, provide the x and y mappings, and optionally a color mapping to differentiate categories.

    import { Canvas, Chart, Interval } from '@antv/f2';
    const data = [
      { genre: 'Sports', sold: 5 },
      { genre: 'Strategy', sold: 10 },
      { genre: 'Action', sold: 20 },
      { genre: 'Shooter', sold: 20 },
      { genre: 'Other', sold: 40 },
    ];
    
    <Canvas context={context}>
      <Chart data={data}>
        <Interval x="genre" y="sold" color="genre" />
      </Chart>
    </Canvas>;