Vega-Embed

repository·main·Indexed 17 days ago

https://github.com/vega/vega-embed

A lightweight utility for embedding interactive Vega and Vega-Lite visualizations into web applications. It supports loading specifications from source text, parsed JSON, or URLs, and provides features such as specification patching, action links (e.g., "View Source"), built-in tooltips, and integration with Observable. The library includes the `embed()` function for rendering views and a `container()` function for interactive environments.

Tokens
3.7K
Snippets
12
Records
20
Agent score
68%

What's inside vega-embed

  1. Embed Vega and Vega-Lite views

    main

    Vega-Embed is a utility for embedding interactive Vega and Vega-Lite visualizations into web pages. It supports loading specifications from source text, parsed JSON, or URLs.

    Key features include:

    • Patching Vega specs to add custom functionality.
    • Adding action links like "View Source" and "Open in Vega Editor".
    • Built-in support for Vega Tooltip and Vega Themes (Note: Themes are currently experimental).
    • Seamless integration with Observable.
  2. Embed Vega in Observable

    main

    In Observable notebooks, you can use require to load the library and then use the viewof syntax to create reactive inputs from your charts.

    Example usage: embed = require('vega-embed@6') viewof view = embed(...)

    // In an Observable cell
    embed = require('vega-embed@6');
    viewof view = embed(container, spec);
  3. Embed Vega directly in the browser via CDN

    main

    To use Vega-Embed directly in an HTML file without a build step, import vega, vega-lite, and vega-embed from a CDN like jsDelivr. Ensure you replace [VERSION] with the appropriate major versions (e.g., vega@5, vega-lite@5, vega-embed@6).

    Use the vegaEmbed(container, spec) function, which returns a Promise that resolves to a result object containing the Vega view instance in result.view.

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <!-- Import Vega & Vega-Lite -->
        <script src="https://cdn.jsdelivr.net/npm/vega@5"></script>
        <script src="https://cdn.jsdelivr.net/npm/vega-lite@5"></script>
        <!-- Import vega-embed -->
        <script src="https://cdn.jsdelivr.net/npm/vega-embed@6"></script>
      </head>
      <body>
        <div id="vis"></div>
    
        <script type="text/javascript">
          var spec = 'https://raw.githubusercontent.com/vega/vega/master/docs/examples/bar-chart.vg.json';
          vegaEmbed('#vis', spec)
            .then(function (result) {
              // Access the Vega view instance as result.view
            })
            .catch(console.error);
        </script>
      </body>
    </html>
  4. Embed Vega using JavaScript or TypeScript

    main

    For modern web development workflows, install vega-embed via npm and import it into your module. This approach requires a bundler (like Webpack or Rollup) and a transpiler (like TypeScript) to work in the browser.

    Use the embed(container, spec) function with await to handle the returned Promise.

    import embed from 'vega-embed';
    
    const spec = {
      // ... your Vega or Vega-Lite specification
    };
    
    const result = await embed('#vis', spec);
    
    // Access the Vega view instance
    console.log(result.view);
  5. Build vega-embed.js from source

    main

    To build the vega-embed.js and vega-embed.min.js files and view the test examples, follow these steps using npm:

    1. Install dependencies: npm install
    2. Build the project: npm run build
    3. Start a local webserver: npm run start

    After starting the server, you can view the test pages at http://localhost:8000/test-vg.html (for Vega) or http://localhost:8000/test-vl.html (for Vega-Lite).

    npm install
    npm run build
    npm run start
  6. How `embed()` determines the visualization mode

    main

    Vega-Embed automatically detects whether a specification is Vega or Vega-Lite using guessMode().

    1. Schema Detection: If the spec contains a $schema property, the library parses the URL to determine the library and version.
    2. Heuristic Fallback: If no schema is present, it checks for Vega-Lite specific keys (mark, encoding, layer, hconcat, etc.). If none are found, it looks for Vega specific keys (marks, signals, scales, etc.).
    3. Manual Override: You can force a mode by providing the mode option in EmbedOptions ('vega' or 'vega-lite').
  7. Support container sizing for responsive Vega-Lite specs

    main
    When using Vega-Lite's container sizing (responsive width and height), the visualization will attempt to fill its parent. To ensure correct sizing, you must explicitly set the width (and/or height) of the DOM element passed to the vegaEmbed function via CSS.
  8. Send cookies when loading data in Vega-Embed

    main

    By default, the Vega loader does not send the credentials of the current page with requests. To include cookies or other credentials when loading data, pass a loader configuration object within the embed options. Specifically, set http.credentials to 'same-origin'.

    vegasEmbed('#vis', spec, { loader: { http: { credentials: 'same-origin' } } });
  9. Use the container() function in Observable

    main

    The container(spec, [opt]) function is specifically designed for use in interactive environments like Observable. It returns a Promise that resolves to an HTML element that has the Vega View instance attached to its value property.

    Arguments

    • spec (String | Object): A URL string to a Vega specification or a parsed JSON Vega/Vega-Lite specification object.
    • opt (Object, optional): A configuration object for embedding.

    Return Value

    A Promise resolving to an HTML element where element.value is the Vega View instance.

    // In an Observable cell
    container(spec, { renderer: 'svg' }).then(el => {
      const view = el.value;
      // Use the view
    });
  10. Use the embed() function to embed Vega visualizations

    main

    The embed(el, spec, [opt]) function is the primary way to add a Vega or Vega-Lite visualization to a web page using the Vega-Embed npm package. It returns a Promise that resolves to a result object containing the instantiated Vega View, the original specification, the compiled Vega specification, and a finalize method.

    Arguments

    • el (String): A DOM element or CSS selector where the view will be added.
    • spec (String | Object): A URL string to a Vega specification or a parsed JSON Vega/Vega-Lite specification object.
    • opt (Object, optional): A configuration object for embedding.

    Result Object

    PropertyTypeDescription
    viewViewThe instantiated Vega View instance.
    specObjectA copy of the parsed JSON Vega or Vega-Lite spec.
    vgSpecObjectThe compiled Vega spec.
    finalizeFunctionA method to unregister timers and event listeners. Call this when the view is no longer needed to prevent memory leaks.

    Note: Internet Explorer requires a Promise polyfill to work with Vega-Embed.

    import * as vegaEmbed from 'vega-embed';
    
    const spec = { ... }; // Your Vega or Vega-Lite spec
    
    vegaEmbed.embed('#vis', spec, { renderer: 'canvas' }).then(result => {
      // Use the view instance
      console.log(result.view);
      
      // When finished, clean up
      // result.finalize();
    });