Dash Cytoscape

repository·main·Indexed 20 days ago

https://github.com/plotly/dash-cytoscape

A Dash component library providing Python and R wrappers around Cytoscape.js for creating interactive, customizable network visualizations. It includes support for various graph layouts, custom context menus, image generation (PNG, JPG, SVG), and the CyLeaflet extension for geospatial mapping layers.

Tokens
4.2K
Snippets
10
Records
18
Agent score
71%

What's inside dash-cytoscape

  1. What is CyLeaflet and how does it work?

    main

    CyLeaflet is a Dash component included with Dash Cytoscape that adds a geospatial mapping layer to Cytoscape graphs. It allows you to render nodes at specific geographic locations by specifying latitude and longitude in the node data.

    How it works

    CyLeaflet uses the Dash All-in-One Component pattern. It is a composite component that wraps several underlying components to synchronize a Cytoscape canvas with a Leaflet map canvas:

    1. Dash Cytoscape: Handles the graph rendering.
    2. Dash Leaflet: Handles the geospatial map layer.
    3. dcc.Store: Holds the element data used for coordinate transformation.
    4. html.Divs: Provide styling to align the Cytoscape canvas exactly on top of the Leaflet canvas.
    5. Clientside Callbacks: Link the components together to ensure synchronization.

    Important: Updating Graph Elements

    You cannot update Cytoscape nodes directly by modifying the elements property of the component. Doing so skips a critical transformation step where lat and lon coordinates are converted into the (x, y) canvas positions required to align with the map.

    To update the graph, you must update the data property of the internal dcc.Store instance. The component uses a callback to transform these coordinates and then update the Cytoscape elements property automatically.

  2. Install and use dash-cytoscape in R

    main

    To use Dash Cytoscape in R, install the necessary dependencies via install.packages and then install the dash-cytoscape package from GitHub using devtools.

    # Prerequisites
    install.packages(c("devtools", "dash"))
    
    # Install dash-cytoscape
    devtools::install_github("plotly/dash-cytoscape")
  3. Install dash-cytoscape in Python

    main

    To use Dash Cytoscape in a Python project, you must first ensure dash is installed. Then, install the library using pip.

    If you require the CyLeaflet mapping extension, install the optional leaflet dependencies using the bracket syntax.

    # Install core library
    pip install dash-cytoscape
    
    # Install with CyLeaflet mapping extension support
    pip install dash-cytoscape[leaflet]
  4. Handle node and edge tap events

    main

    When a user interacts with elements, Dash Cytoscape provides read-only data via tapNode, tapNodeData, tapEdge, and tapEdgeData.

    tapNode / tapEdge (Full Objects): Contains complete element dictionaries including data, position, style, classes, and relationship data (like ancestorsData or childrenData for nodes).

    tapNodeData / tapEdgeData (Data Dictionaries): Contains only the data dictionary associated with the tapped element.

    Other Selection/Hover Data:

    • selectedNodeData (array): Data dictionaries of all currently selected nodes.
    • selectedEdgeData (array): Data dictionaries of all currently selected edges.
    • mouseoverNodeData (object): Data dictionary of the currently hovered node.
    • mouseoverEdgeData (object): Data dictionary of the currently hovered edge.
    • clearOnUnhover (bool): If true, mouseover data is cleared when the user stops hovering.
  5. Basic usage of Cytoscape in Python

    main

    To create a basic network visualization, use the dash_cytoscape.Cytoscape component. You define the network using an elements list containing dictionaries for nodes and edges. Nodes typically include data (with id and label) and an optional position. Edges include data with source and target IDs. The layout property determines how elements are positioned (e.g., 'preset').

    import dash
    import dash_cytoscape as cyto
    from dash import html
    
    app = dash.Dash(__name__)
    app.layout = html.Div([
        cyto.Cytoscape(
            id='cytoscape',
            elements=[
                {'data': {'id': 'one', 'label': 'Node 1'}, 'position': {'x': 50, 'y': 50}},
                {'data': {'id': 'two', 'label': 'Node 2'}, 'position': {'x': 200, 'y': 200}},
                {'data': {'source': 'one', 'target': 'two','label': 'Node 1 to 2'}}
            ],
            layout={'name': 'preset'}
        )
    ])
    
    if __name__ == '__main__':
        app.run(debug=True)
  6. Enable external layouts and SVG generation

    main

    By default, Cytoscape uses built-in layouts. To use additional external layouts or to enable the generation of SVG images, call cyto.load_extra_layouts() at the start of your application.

    import dash
    import dash_cytoscape as cyto
    from dash import html
    
    # Enables external layouts and SVG image generation
    cyto.load_extra_layouts()
    
    app = dash.Dash(__name__)
    app.layout = html.Div([
        cyto.Cytoscape(...)
    ])
  7. Define a custom context menu

    main

    The contextMenu property accepts an array of objects to define a custom menu. Each item requires an id and a label.

    Behavior Options:

    1. Built-in functions: Set onClick to 'remove', 'add_node', or 'add_edge'.
    2. Custom JavaScript functions: Set onClickCustom to a string referring to a function in the dashCytoscapeFunctions namespace.
    3. Dash Callbacks: Omit both onClick and onClickCustom. This will update the contextMenuData property and trigger a Dash callback.

    Menu Item Properties:

    • id (string, required): Unique identifier.
    • label (string, required): Display text.
    • tooltipText (string): Hover text.
    • availableOn (array): Where the item appears (e.g., ['node'], ['edge'], or ['canvas']).
  8. Generate the extra layouts bundle for dash-cytoscape

    main

    The webpack.prod.extra.config.js configuration is used specifically to generate a specialized production bundle named dash_cytoscape_extra.min.js. This bundle is intended for the version of dash-cytoscape that includes extra layouts. It uses ./src/lib/extra_index.js as the entry point and sets the mode to production.

    // This webpack config is intended solely for generating the bundle for the extra layouts version of
    // dash_cytoscape.min.js
    
    const config = require('./webpack.config.js');
    
    config.entry = {main: './src/lib/extra_index.js'};
    config.output = {filename: 'dash_cytoscape_extra.min.js'};
    config.mode = 'production';
    
    module.exports = config;
  9. Configure graph layouts

    main

    The layout property is a dictionary specifying how to position elements in your graph. The name key is required.

    Available Default Layouts:

    • random: Randomly assigns positions.
    • preset: Uses the position key in element dictionaries.
    • circle: Single-level circle.
    • concentric: Multi-level circle.
    • grid: Square grid (can be configured with rows and cols).
    • breadthfirst: Tree structure using BFS (can be configured with roots).
    • cose: Force-directed physics simulation.

    External Layouts: To use external layouts, you must call dash_cytoscape.load_extra_layouts() in your Python code before initializing the Dash app. Available external layouts include:

    • cose-bilkent, fcose, cola, euler, spread, dagre, klay.

    Common Layout Options (accepted by all):

    • fit (bool): Whether to render nodes to fit the canvas.
    • padding (number): Padding around the sides of the canvas.
    • animate (bool): Whether to animate position changes.
    • animationDuration (number): Duration of animation in milliseconds.
    • boundingBox (object): Constrains layout to an area using {x1, y1, x2, y2} or {x1, y1, w, h}.
  10. Control viewport panning and zooming

    main

    You can control the initial state and user interaction capabilities of the graph viewport using the following properties:

    Initial State:

    • pan (object): Initial position {x, y}.
    • zoom (number): Initial zoom level.

    Interaction Controls:

    • panningEnabled (bool): Enables/disables overall panning.
    • userPanningEnabled (bool): Enables/disables user-driven panning (e.g., dragging background).
    • zoomingEnabled (bool): Enables/disables overall zooming.
    • userZoomingEnabled (bool): Enables/disables user-driven zooming.
    • wheelSensitivity (number): Sensitivity of the scroll wheel for zooming.
    • minZoom (number): Minimum allowed zoom level.
    • maxZoom (number): Maximum allowed zoom level.
    • boxSelectionEnabled (bool): Enables drag-box selection (requires tap-hold to pan).
  11. Generate graph images

    main

    The generateImage property allows you to export the current graph as an image. This property is cleared after the image is generated and must be invoked via a Dash callback after the component has rendered.

    Configuration Options:

    • type (string): Output format ('svg', 'png', 'jpg', or 'jpeg').
    • action (string):
      • 'store': Stores image data in imageData and triggers Dash callbacks (supports jpg and png).
      • 'download': Downloads the file client-side (no imageData callback fired).
      • 'both': Performs both actions (default).
    • filename (string): Name of the downloaded file (default: 'cyto').
    • options (object): Additional options for the underlying Cytoscape.js export function.
  12. Use the contextMenu prop for right-click menus

    main

    The contextMenu prop allows you to define a custom right-click menu. Each item in the list should be a dictionary with:

    • id: A unique identifier for the menu item.
    • label: The text displayed in the menu.
    • tooltipText: Optional text for a tooltip.
    • availableOn: An array specifying where the item appears. Valid values are 'node', 'edge', or 'canvas'.
    • onClick: (Optional) A predefined string for default actions: 'remove', 'add_node', or 'add_edge'.
    • onClickCustom: (Optional) A string referring to a custom JavaScript function defined in the window.dashCytoscapeFunctions namespace.
    context_menu = [
        {
            'id': 'remove_item',
            'label': 'Remove Element',
            'onClick': 'remove',
            'availableOn': ['node', 'edge']
        },
        {
            'id': 'custom_action',
            'label': 'My Custom Action',
            'onClickCustom': 'myCustomJsFunction',
            'availableOn': ['canvas']
        }
    ]