FunnelGraph.js

repository·master·Indexed 43 days ago

https://github.com/greghub/funnel-graph-js

An SVG Funnel Graph Javascript Library (v1.4.2) for generating horizontal and vertical funnel charts. It supports solid colors, gradients, and two-dimensional data breakdowns to visualize sub-segments within main stages. The library provides a FunnelGraph class with methods for drawing, updating data, and toggling orientations.

Tokens
3.4K
Snippets
10
Records
12
Agent score
56%

What's inside FunnelGraph.js

  1. Configure Two-dimensional funnel graphs

    master

    A two-dimensional funnel graph allows you to visualize sub-segments within each main stage. You provide subLabels for the breakdown and nested arrays in values and colors to match the sub-labels.

    In a 2D graph, each segment can have its own unique color or gradient. If a gradient is used, the global gradientDirection option applies to all segments.

    data: {
        labels: ['Impressions', 'Add To Cart', 'Buy'],
        subLabels: ['Direct', 'Social Media', 'Ads'],
        colors: [
            ['#FFB178', '#FF78B1', '#FF3C8E'],
            'red',
            ['blue']
        ],
        values: [
            [2000, 4000, 6000],
            [3000, 1000, 1700],
            [200, 30, 130]
        ]
    }
  2. Define data for a simple funnel graph

    master

    There are three ways to define data:

    1. Simple Array: Pass an array of numbers. This creates a graph without titles. data: [12000, 5700, 360]

    2. Explicit Object: Pass an object containing labels, values, and optionally colors. This is the most explicit way.

      data: {
          labels: ['Impressions', 'Add To Cart', 'Buy'],
          colors: ['orange', 'red'],
          values: [12000, 5700, 360]
      }
    3. Two-dimensional Data: Break down segments into sub-categories using subLabels and nested arrays for colors and values.

    data: {
        labels: ['Impressions', 'Add To Cart', 'Buy'],
        subLabels: ['Direct', 'Social Media', 'Ads'],
        colors: [
            ['#FFB178', '#FF78B1', '#FF3C8E'],
            'red',
            ['blue']
        ],
        values: [
            [2000, 4000, 6000],
            [3000, 1000, 1700],
            [200, 30, 130]
        ]
    }
  3. Install FunnelGraph.js

    master

    You can install FunnelGraph.js via NPM, use a CDN, or download the files directly.

    NPM

    npm i funnel-graph-js

    CDN

    Include the following in your HTML:

    <link rel="stylesheet" type="text/css" href="https://unpkg.com/funnel-graph-js@1.3.9/dist/css/main.min.css">
    <link rel="stylesheet" type="text/css" href="https://unpkg.com/funnel-graph-js@1.3.9/dist/css/theme.min.css">
    
    <script src="https://unpkg.com/funnel-graph-js@1.3.9/dist/js/funnel-graph.min.js"></script>

    Download

    Download the repository ZIP and include funnel-graph.js (or .min.js) and main.css (or .min.css). It is highly recommended to also include theme.min.css to ensure labels and legends are styled correctly.

  4. Create a two-dimensional funnel graph

    master

    A two-dimensional funnel graph is created by providing an array of arrays for the values property in the data object. This allows for multiple sub-segments within each main funnel step.

    When using 2D mode:

    • subLabels can be provided to name the sub-segments.
    • subLabelValue can be set to either 'percent' (default) or a number format to control how sub-segment values are displayed in the labels.
    • The graph will automatically generate a legend for the sub-labels.
    const graph = new FunnelGraph({
        container: '#my-container',
        data: {
            labels: ['Step 1', 'Step 2'],
            subLabels: ['Segment A', 'Segment B'],
            values: [
                [50, 50], // Step 1: 50 in A, 50 in B
                [30, 20]  // Step 2: 30 in A, 20 in B
            ],
            colors: [['#ff0000', '#ffcccc'], ['#00ff00', '#ccffcc']]
        },
        subLabelValue: 'percent'
    });
    
    graph.draw();
  5. Initialize and draw a FunnelGraph

    master

    To create a funnel chart, instantiate the FunnelGraph class with an options object and call the .draw() method. The container option must be either a CSS selector string or an HTMLElement where the graph will be rendered.

    Common options include:

    • container: (string|HTMLElement) The target element.
    • data: (object) The data object containing labels, values, and optionally subLabels and colors.
    • direction: ('vertical'|'horizontal') The primary axis of the graph.
    • displayPercent: (boolean) Whether to show percentage labels.
    • width / height: (number) Dimensions of the graph.
    • gradientDirection: ('vertical'|'horizontal') The direction of color gradients.
    import FunnelGraph from 'funnel-graph-js';
    
    const graph = new FunnelGraph({
        container: '#my-container',
        data: {
            labels: ['Step 1', 'Step 2', 'Step 3'],
            values: [100, 50, 25],
            colors: ['#ff0000', '#00ff00', '#0000ff']
        },
        direction: 'vertical',
        displayPercent: true
    });
    
    graph.draw();
  6. Basic Usage of FunnelGraph.js

    master

    To create a funnel chart, instantiate the FunnelGraph class with a configuration object and call the .draw() method. You must provide a container selector and a data object.

    By default, the library calculates percentages automatically, treating the largest number as 100% and calculating others as a fraction of that maximum.

    var graph = new FunnelGraph({
        container: '.funnel',
        gradientDirection: 'horizontal',
        data: {
            labels: ['Impressions', 'Add To Cart', 'Buy'],
            values: [12000, 5700, 360]
        },
        displayPercent: true,
        direction: 'horizontal'
    });
    
    graph.draw();
  7. Configure FunnelGraph options

    master

    The FunnelGraph constructor accepts an options object with the following schema:

    KeyTypeDescription
    containerstring or HTMLElementRequired. The selector or element to host the graph.
    dataobjectRequired. Contains labels (Array), values (Array or Array of Arrays), subLabels (Array, optional), and colors (Array, optional).
    direction'vertical' or 'horizontal'The orientation of the funnel.
    gradientDirection'vertical' or 'horizontal'The direction of the color gradients.
    displayPercentbooleanWhether to display percentage values in the labels.
    heightnumberExplicit height of the graph.
    widthnumberExplicit width of the graph.
    subLabelValue'percent' or numberHow sub-segment values are formatted in 2D graphs.
    data.colorsArrayCustom colors for segments or gradients.
  8. Reference: FunnelGraph configuration options

    master

    The following options are used when instantiating new FunnelGraph(options).

    | Option | Description | Type | Required | Options | Default | Example |
    |--------|-------------|------|----------|---------|---------|---------|
    | `container` | Selector of the element that will hold the chart | `string` | Yes | | | '.funnel-container' |
    | `direction` | Whether the chart visualization is displayed vertically or horizontally | `string` | No | 'vertical', 'horizontal' | 'horizontal' | | 
    | `gradientDirection` | Whether the gradient applied to the segments of the graph is displayed from top to bottom or from left to right | `string` | No | 'vertical', 'horizontal' | 'horizontal' | | 
    | `displayPercent` | Whether to display the automatically calculated percentage values below the labels | `boolean` | No | `true`, `false` | `true` | | 
    | `data` | Object containing information about values, labels and colors of the chart | `object` | Yes | | | |
    | `width` | Width of the funnel graph | `number` | No | | Container width | 800 |
    | `height` | Height of the funnel graph | `number` | No | | Container height | 300 |
    | `subLabelValue` | Whether display percentage or real value of segment | `string` | No | `percent`, `raw` | `percent` |
  9. Reference: FunnelGraph methods

    master

    Use these methods on a FunnelGraph instance to manipulate the chart after initialization.

    | Method | Description | Example |
    |--------|-------------|---------|
    | `makeVertical()` | Display chart vertically | |
    | `makeHorizontal()` | Display chart horizontally | |
    | `toggleDirection()` | Toggle direction of chart | |
    | `gradientMakeVertical()` | Display gradient on all sections from top to bottom | |
    | `gradientMakeHorizontal()` | Display gradient on all sections from left to right | |
    | `gradientToggleDirection()` | Toggle direction of gradient on all sections | |
    | `updateHeight()` | Update funnel graph height | |
    | `updateWidth()` | Update funnel graph width | |
    | `updateData({data})` | Update funnel graph data | ```labels: ['Stage 1', 'Stage 2', 'Stage 3']``` |
    | `update({options})` | Update funnel options | ```gradientDirection: 'horizontal', data: {...}, displayPercent: true, direction: 'horizontal', height: 300, width: 500``` |
  10. Update an existing FunnelGraph

    master

    Use the .update(options) method to modify an existing graph without re-instantiating it. This method allows for efficient updates to dimensions, direction, gradient direction, or the underlying data.

    Supported update keys:

    • displayPercent: Toggles percentage visibility.
    • height / width: Updates graph dimensions.
    • gradientDirection: Changes gradient orientation.
    • direction: Changes graph orientation (vertical/horizontal).
    • data: Updates the entire dataset (labels, values, subLabels, etc.).
    // Update only the width and direction
    graph.update({
        width: 800,
        direction: 'vertical'
    });
    
    // Update the data entirely
    graph.update({
        data: {
            labels: ['New Step 1', 'New Step 2'],
            values: [10, 5]
        }
    });
  11. Change FunnelGraph orientation and gradients

    master

    You can programmatically change the orientation or gradient direction of a rendered graph using these methods:

    Orientation:

    • makeVertical(): Sets direction to vertical.
    • makeHorizontal(): Sets direction to horizontal.
    • toggleDirection(): Switches between vertical and horizontal.

    Gradients:

    • gradientMakeVertical(): Sets gradient direction to vertical.
    • gradientMakeHorizontal(): Sets gradient direction to horizontal.
    • gradientToggleDirection(): Switches between vertical and horizontal gradients.