Plotly.js

repository·master·Indexed 12 days ago

https://github.com/plotly/plotly.js

An open source JavaScript graphing library for creating interactive, high-quality data visualizations, including statistical, 3D, scientific, and financial charts. Version 3.7.0 serves as the engine for Plotly's Python and R implementations. It supports installation via npm, CDN script tags, and native ES6 modules, and provides options for building custom bundles to optimize size.

Tokens
38.9K
Snippets
133
Records
175
Agent score
97%

What's inside Plotly.js

  1. Alternative ways to require or build plotly.js

    master
    Instead of the full library, you can integrate plotly.js into your application by requiring or importing specific distributed packages or individual files from the lib index. This allows for more granular control over the bundle size and dependencies depending on your specific requirements.
  2. Understand plotly.js bundle types

    master

    Plotly.js provides two main ways to manage bundles:

    1. Official Bundles: Complete or partial bundles distributed via npm and CDN.
    2. Custom Bundles: You can create your own custom bundles to optimize the bundle size based on your specific requirements (e.g., including only specific chart types).
  3. Load plotly.js via script tag

    master

    You can load plotly.js directly in the browser using a <script> tag from a CDN. The Plotly object is added to the window scope. Use Plotly.newPlot(graphDiv, data, layout) to render charts.

    Important: For versions v2 and higher, you must specify an exact version in the URL (e.g., plotly-3.7.0.min.js) because the plotly-latest alias is no longer updated and remains stuck at v1.58.5.

    <head>
        <script src="https://cdn.plot.ly/plotly-3.7.0.min.js" charset="utf-8"></script>
    </head>
    <body>
        <div id="gd"></div>
    
        <script>
            Plotly.newPlot("gd", {
                "data": [{ "y": [1, 2, 3] }],
                "layout": { "width": 600, "height": 400}
            })
        </script>
    </body>
  4. Install plotly.js as a Node module

    master

    To use plotly.js in a Node.js environment, install the ready-to-use distributed minified bundle via npm. You can then use either ES6 import or CommonJS require to access the Plotly object.

    npm i --save plotly.js-dist-min
    // ES6 module
    import Plotly from 'plotly.js-dist-min'
    
    // CommonJS
    var Plotly = require('plotly.js-dist-min')
  5. Load plotly.js using native ES6 modules in the browser

    master

    You can use native ES6 import within a <script type="module"> tag to load plotly.js from a CDN.

    <script type="module">
        import "https://cdn.plot.ly/plotly-3.7.0.min.js"
        Plotly.newPlot("gd", [{ y: [1, 2, 3] }])
    </script>
  6. Configure MathJax for mathematical rendering

    master

    To render mathematical expressions in plots, load MathJax. You can use either version 2 or version 3. When using MathJax version 3, you can use chtml output for other parts of the page alongside svg output for the plotly graph.

    <!-- MathJax version 2 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_SVG.js"></script>
    
    <!-- MathJax version 3 -->
    <script src="https://cdn.jsdelivr.net/npm/mathjax@3.2.2/es5/tex-svg.js"></script>
  7. Handle multiple WebGL graphs on a single page

    master

    If your application needs to display several WebGL-based graphs on the same page, load the virtual-webgl script (for WebGL 1) before loading any other scripts.

    <script src="https://unpkg.com/virtual-webgl@1.0.6/src/virtual-webgl.js"></script>
  8. Build a custom plotly.js bundle

    master

    If the distributed packages do not meet your needs or you want to optimize bundle size, you can build a custom bundle from source.

    Prerequisites

    Ensure your Node/npm versions match your plotly.js version requirements:

    • plotly.js < 2.5: Node 12 / npm 6
    • plotly.js >= 2.5: Node 16 / npm 8
    • plotly.js >= 2.35: Node 18 / npm 10

    Setup Steps

    1. Clone the repository at a specific version:
      git clone --branch <version> https://github.com/plotly/plotly.js.git
      (If already cloned, use git fetch and git checkout <version> to switch versions).
    2. Navigate to the directory and install dependencies:
      cd plotly.js
      npm i
    git clone --branch <version> https://github.com/plotly/plotly.js.git
    cd plotly.js
    npm i
  9. Integrate plotly.js with Angular CLI

    master

    Because Angular uses webpack internally and restricts direct webpack configuration, you must use the @angular-builders/custom-webpack builder and ify-loader to correctly process plotly.js files.

    Step 1: Install dependencies

    Install the custom webpack builder and ify-loader (version 1.1.0 or higher):

    npm install @angular-builders/custom-webpack ify-loader@^1.1.0

    Step 2: Create a custom webpack configuration

    Create a file named extra-webpack.config.js in the same directory as your angular.json. This configuration uses ify-loader to handle the .js files within the plotly.js node module.

    const path = require('path');
    
    module.exports = {
        module: {
            rules: [
                {
                    test: /\.js$/,
                    include: [
                        path.resolve(__dirname, "node_modules/plotly.js")
                    ],
                    loader: 'ify-loader'
                }
            ]
        },
    };

    Step 3: Update angular.json

    Modify your angular.json to use the custom builder and point to your new configuration file. You must update the builder and the customWebpackConfig options for each project defined in your workspace.

    Ensure projects.[PROJECT_NAME].architect.build.builder is set to @angular-builders/custom-webpack:browser and that customWebpackConfig is configured as shown below.

    {
      "projects": {
        "MY_PROJECT_NAME": {
          "architect": {
            "build": {
              "builder": "@angular-builders/custom-webpack:browser",
              "options": {
                "customWebpackConfig": {
                  "path": "./extra-webpack.config.js",
                  "replaceDuplicatePlugins": true,
                  "mergeStrategies": {"module.rules": "merge"}
                }
              }
            }
          }
        }
      }
    }
  10. Emit plotly_clickannotation event

    master

    When an annotation is clicked, Plotly.js can emit a plotly_clickannotation event. This event is triggered if the annotation has captureevents set to true or if the global edit context allows annotation text interaction.

    The event data object contains:

    • index: The index of the annotation in the annotations array.
    • annotation: The original input object (options._input).
    • fullAnnotation: The complete annotation options object.
    • event: The original D3 event.
    • subplotId: (Optional) The ID of the subplot if the annotation is not a 2D/paper-ref annotation.
  11. Configure a Surface trace

    master

    The surface trace type is used to create 3D surface plots. The primary data is provided via the z attribute, which must be a 2D array representing the heights/values at each coordinate.

    Key configuration details:

    • Coordinates: The z array defines the surface. You can provide x and y as 1D arrays or 2D arrays (for parametric surfaces). If x and y are omitted, they default to a linear scale starting at 0 with a unit step.
    • Coloring: By default, the color scale is mapped to the z values. To use a custom color scale independent of the height, use the surfacecolor attribute (which must also be a 2D array).
    • Color Scale Bounds: You can control the color scale range using cmin and cmax.
    {
      "type": "surface",
      "z": [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
      "x": [1, 2, 3],
      "y": [1, 2, 3],
      "surfacecolor": [[...]],
      "cmin": 0,
      "cmax": 10
    }
  12. Use the 'table' trace type for grid data visualization

    master

    The table trace type is used to create a table view for detailed data viewing. Data is arranged in a grid of rows and columns.

    Key Characteristics:

    • Data Layout: The table uses a column-major order, meaning the grid is represented as a vector of column vectors.
    • Styling: Most styling can be applied at the column, row, or individual cell level.
    • Trace Type: In a Plotly data array, this trace is identified by type: 'table'.
    • Categories: This trace belongs to the noOpacity category.
    // Example usage in a Plotly plot
    var data = [{
      type: 'table',
      header: { bgcolor: 'black', font: { color: 'white', size: 12 } },
      cells: { values: [[1, 2, 3], [4, 5, 6]] }
    }];
    
    Plotly.newPlot('myDiv', data);