Code Monkey home page Code Monkey logo

vega-embed's Introduction

Vega-Embed

npm version Build Status codecov code style: prettier

Vega-Embed makes it easy to embed interactive Vega and Vega-Lite views into web pages. With Vega Embed, you can:

  • Load Vega/Vega-Lite specs from source text, parsed JSON, or URLs.
  • Patch Vega specs (even ones generated from Vega-Lite) to add additional functionality; for example, see Rotating Earth.
  • Add action links such as "View Source" and "Open in Vega Editor".
  • Includes Vega Tooltip.
  • Includes Vega Themes. Experimental: themes are not stable yet

Vega-Lite works well with Observable. Learn how to use it in our example notebook.

Basic Examples

Directly in the Browser

You can import Vega-Embed from a local copy or (as shown below) from jsDelivr. Please replace [VERSION] with the correct Vega, Vega-Lite, and Vega-Embed versions. We recommend that you specify the major versions (vega@5, vega-lite@5, vega-embed@6).

<!DOCTYPE html>
<html>
<head>
  <!-- Import Vega & Vega-Lite (does not have to be from CDN) -->
  <script src="https://cdn.jsdelivr.net/npm/vega@[VERSION]"></script>
  <script src="https://cdn.jsdelivr.net/npm/vega-lite@[VERSION]"></script>
  <!-- Import vega-embed -->
  <script src="https://cdn.jsdelivr.net/npm/vega-embed@[VERSION]"></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 (https://vega.github.io/vega/docs/api/view/) as result.view
  }).catch(console.error);
</script>
</body>
</html>

Look at the example online in the Vega-Embed Block.

JavaScript or TypeScript

The basic example below needs to be transpiled and bundled (using rollup, webpack, etc..) before it can be loaded in a browser.

import embed from 'vega-embed';

const spec = {
  ...
}

const result = await embed('#vis', spec);

console.log(result.view);

In Observable

You can require embed with embed = require('vega-embed@6') and then embed a chart with viewof view = embed(...). Check the our example notebook for more details.

API Reference

When using a script tag, the default export of Vega-Embed is a wrapper function that automatically chooses between embed and container based on the provided arguments. Vega-Embed provides this convenience for imports in interactive environments like Observable. When using the Vega-Embed npm package, the default export is the embed function.

# embed(el, spec[, opt]) <>

Returns a Promise that resolves to a result object. The result object contains:

Property Type Description
view String The instantiated Vega View instance.
spec Object A copy of the parsed JSON Vega or Vega-Lite spec.
vgSpec Object The compiled Vega spec.
finalize Function A method to prepare embed to be removed. To prevent unwanted behaviors and memory leaks, this method unregisters any timers and removes any event listeners the visualization has registered on external DOM elements. Applications should invoke this method when a Embed or the View instance is no longer needed. This method calls view.finalize.

The embed function accepts the following arguments:

Property Type Description
el String A DOM element or CSS selector indicating the element on the page in which to add the embedded view.
spec String / Object String : A URL string from which to load the Vega specification. This URL will be subject to standard browser security restrictions. Typically this URL will point to a file on the same host and port number as the web page itself.
Object : The Vega/Vega-Lite specification as a parsed JSON object.
opt Object (Optional) A JavaScript object containing options for embedding.

Note: Internet Explorer does not support the ES6 Promise feature. To make it work correctly, please follow the instructions on the Vega website.

# container(spec[, opt]) <>

Returns a Promise* that resolves to an HTML element with the Vega View instance as the value property. The function is designed to work with Observable. The container function accepts the following arguments:

Property Type Description
spec String / Object String : A URL string from which to load the Vega specification. This URL will be subject to standard browser security restrictions. Typically this URL will point to a file on the same host and port number as the web page itself.
Object : The Vega/Vega-Lite specification as a parsed JSON object.
opt Object (Optional) A JavaScript object containing options for embedding.

Options

You can configure Vega Embed with an options object. You can pass options as an argument to the embed function or as usermeta.embedOptions as part of the Vega or Vega-Lite specification.

var opt = {
  mode: ...,

  config: ...,
  theme: ...,

  defaultStyle: ...,

  bind: ...,

  // view config options
  renderer: ...,
  loader: ...,
  logLevel: ...,

  tooltip: ...,

  patch: ...,

  width: ...,
  height: ...,
  padding: ...,

  actions: {
    export: ...,
    source: ...,
    compiled: ...,
    editor: ...
  },

  scaleFactor: ...,

  editorUrl: ...,

  sourceHeader: ...,
  sourceFooter: ...,

  hover: {
    hoverSet: ...,
    updateSet: ...,
  },

  downloadFileName: ...,

  formatLocale: ...,
  timeFormatLocale: ...,
  expressionFunctions: ...,

  ast: ...,
  expr: ...,

  i18n: {
    COMPILED_ACTION: ...,
    EDITOR_ACTION: ...,
    PNG_ACTION: ...,
    SOURCE_ACTION: ...,
    SVG_ACTION: ...
  }
}
Property Type Description
mode String If specified, tells Vega-Embed to parse the spec as vega or vega-lite. Vega-Embed will parse the $schema url if the mode is not specified. Vega-Embed will default to vega if neither mode, nor $schema are specified.
config String / Object String : A URL string from which to load a Vega/Vega-Lite or Vega-Lite configuration file. This URL will be subject to standard browser security restrictions. Typically this URL will point to a file on the same host and port number as the web page itself.
Object : A Vega/Vega-Lite configuration as a parsed JSON object to override the default configuration options.
theme String If specified, tells Vega-Embed use the theme from Vega Themes. Experimental: we may update themes with minor version updates of Vega-Embed.
defaultStyle Boolean or String If set to true (default), the embed actions are shown in a menu. Set to false to use simple links. Provide a string to set the style sheet (not supported in usermeta).
forceActionsMenu Boolean If set to true, the embed actions are shown in a menu like they would be if the defaultStyle option were truthy. This can be useful when setting defaultStyle to false and defining menu styles in the parent application.
bind String or Element The element that should contain any input elements bound to signals.
renderer String The renderer to use for the view. One of "canvas" (default) or "svg". See Vega docs for details. May be a custom value if passing your own viewClass option.
logLevel Level Sets the current log level. See Vega docs for details.
tooltip Handler or Boolean or Object Provide a tooltip handler, customize the default Vega Tooltip handler, or disable the default handler.
loader Loader / Object Loader : Sets a custom Vega loader. Object : Vega loader options for a loader that will be created.
See Vega docs for details.
patch Function / Object[] / String A function to modify the Vega specification before it is parsed. Alternatively, a JSON-Patch RFC6902 to modify the Vega specification. If you use Vega-Lite, the compiled Vega will be patched. Alternatively to the function or the object, a URL string from which to load the patch can be provided. This URL will be subject to standard browser security restrictions. Typically this URL will point to a file on the same host and port number as the web page itself.
width Number Sets the view width in pixels. See Vega docs for details. Note that Vega-Lite overrides this option.
height Number Sets the view height in pixels. See Vega docs for details. Note that Vega-Lite overrides this option.
padding Number / Object Sets the view padding in pixels. See Vega docs for details.
actions Boolean / Object Determines if action links ("Export as PNG/SVG", "View Source", "View Vega" (only for Vega-Lite), "Open in Vega Editor") are included with the embedded view. If the value is true, all action links will be shown and none if the value is false. This property can take a key-value mapping object that maps keys (export, source, compiled, editor) to boolean values for determining if each action link should be shown. By default, export, source, and editor are true and compiled is false. These defaults can be overridden: for example, if actions is {export: false, source: true}, the embedded visualization will have two links – "View Source" and "Open in Vega Editor". The export property can take a key-value mapping object that maps keys (svg, png) to boolean values for determining if each export action link should be shown. By default, svg and png are true.
scaleFactor Number / Object Number: The number by which to multiply the width and height (default 1) of an exported PNG or SVG image.
Object: The different multipliers for each format ({ svg: <Number>, png: <Number> }). If one of the formats is omitted, the default value is used.
editorUrl String The URL at which to open embedded Vega specs in a Vega editor. Defaults to "http://vega.github.io/editor/". Internally, Vega-Embed uses HTML5 postMessage to pass the specification information to the editor.
sourceHeader String HTML to inject into the head tag of the page generated by the "View Source" and "View Vega" action link. For example, this can be used to add code for syntax highlighting.
sourceFooter String HTML to inject into the end of the page generated by the "View Source" and "View Vega" action link. The text will be added immediately before the closing body tag.
hover Boolean or Object Enable hover event processing. Hover event processing is enabled on Vega by default.
Boolean: Enables/disables hover event processing.
Object: Optional keys (hoverSet, updateSet) to specify which named encoding sets to invoke upon mouseover and mouseout.
i18n Object This property maps keys (COMPILED_ACTION, EDITOR_ACTION, PNG_ACTION, SOURCE_ACTION, SVG_ACTION) to string values for the action's text. By default, the text is in English.
downloadFileName String Sets the file name (default: visualization) for charts downloaded using the png or svg action.
formatLocale Object Sets the default locale definition for number formatting. See the d3-format locale collection for definition files for a variety of languages. Note that this is a global setting.
timeFormatLocale Object Sets the default locale definition for date/time formatting. See the d3-time-format locale collection for definition files for a variety of languages. Note that this is a global setting.
expressionFunctions Object Sets custom expression functions. Maps a function name to a JavaScript function, or an Object with the fn, and visitor parameters. See Vega Expression Functions for more information.
ast Boolean Generate an Abstract Syntax Tree (AST) instead of expressions and use an interpreter instead of native evaluation. While the interpreter is slower, it adds support for Vega expressions that are Content Security Policy (CSP)-compliant.
expr Object Custom Vega Expression interpreter.
viewClass Class Class which extends Vega View for custom rendering.

Common questions

How do I send cookies when loading data?

By default, the Vega loader does not send the credentials of the current page with requests. You can override this behavior by passing {loader: { http: { credentials: 'same-origin' }}} as the embed option.

What CSS should I use to support container sizing?

When using container sizing in Vega-Lite, make sure to set the width of the DOM element you passed to Embed.

Build Process

To build vega-embed.js and view the test examples, you must have Yarn 1 installed.

  1. Run yarn in the Vega-Embed folder to install dependencies.
  2. Run yarn build. This will create vega-embed.js and the minified vega-embed.min.js.
  3. Run a local webserver with yarn start then point your web browser at the test page (e.g., http://localhost:8000/test-vg.html(Vega) or http://localhost:8000/test-vl.html(Vega-Lite)).

Publishing

To make a release, run npm run release.

vega-embed's People

Contributors

activescott avatar alexboss avatar arvind avatar bit-less avatar chris-canipe avatar danmarshall avatar dependabot-preview[bot] avatar dependabot[bot] avatar domoritz avatar fredhohman avatar g3o2 avatar gcheung55 avatar greenkeeper[bot] avatar haldenl avatar hydrosquall avatar jheer avatar joaopalmeiro avatar kanitw avatar keller-mark avatar marcprux avatar metasoarous avatar mostapharoudsari avatar nyurik avatar pydolan avatar syntaxrules avatar vdonato avatar ydlamba avatar yhoonkim avatar yifanwu avatar zacharybys avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vega-embed's Issues

Signal bind element not found: null

Using the latest versions of vega, vega-lite, and vega-embed with a simple example from you code sample, I get the following console error:

ERROR: Signal bind element not found: null
log @ logger.js:3
:
(etc)

I'm calling this from within Angular 5 (TypeScript) as follows:

import vegaEmbed from 'vega-embed';
:
// statically create a spec object from the samples
vlHelloWorld: any = { ... }

In the init function:

vegaEmbed('vega-lite', this.vlHelloWorld, {mode: 'vega-lite'});

Markup:

Please respect semantic versioning

I used v3.5.0 on a project and later upgraded to v3.14.0 and the sorting that I had on my vis broke.

3.5.0 compatible vis spec:

 {
    '$schema': 'https://vega.github.io/schema/vega-lite/v2.json',
    'data': {
      'values': data,
    },
    'transform': [{
      'calculate': 'datum.variation/100',
      'as': 'percent_variation'
    }],
    'width': 400,
    'autosize': {
      'type': 'fit',
      'contains': 'padding',
    },
    'config': {
      'axis': {
        'labelFontSize': 12,
      },
    },
    'encoding': {
      'y': {
        'field': 'name',
        'type': 'ordinal',
        'sort': data.map(x => x.name),
        'axis': {
          'ticks': false,
          'title': '',
        },
      },
      'x': {
        'field': 'value',
        'type': 'quantitative',
        'axis': {
          'ticks': false,
          'orient': 'top',
          'title': data.length ? data[0].unit : 'no data',
        },
      },
    },
    'layer': [
      {
        'mark': 'bar'
      }, {
        'mark': {
          'type': 'text',
          'align': 'right',
          'baseline': 'middle',
          'fontSize': 12,
        },
        'encoding': {
          'text': {'field': 'value', 'type': 'quantitative'}
        }
      },
      {
        'mark': {
          'type': 'text',
          'align': 'left',
          'baseline': 'middle',
          'dx': 10,
          'fontSize': 12,
        },
        'encoding': {
          'text': {
            'field': 'percent_variation',
            'type': 'quantitative',
            'format': '.0%',
          },
          'color': {
            'condition': {
              'test': 'datum[\'percent_variation\'] > 0',
              'value': 'green',
            },
            'value': 'red',
          },
        },
      },
    ],
  };

In order to use 3.14.0, this spec had to be changed to the following:

{
    '$schema': 'https://vega.github.io/schema/vega-lite/v2.json',
    'data': {
      'values': data,
    },
    'transform': [{
      'calculate': 'datum.variation/100',
      'as': 'percent variation'
    }],
    'width': 400,
    'autosize': {
      'type': 'fit-x',
      'contains': 'padding',
    },
    'config': {
      'axis': {
        'labelFontSize': 12,
      },
    },
    'encoding': {
      'tooltip': [
        {'field': 'name', 'type': 'ordinal' },
        {'field': 'value', 'type': 'quantitative'},
        {'field': 'percent variation', 'type': 'quantitative', 'format': '.0%'},
      ],
      'y': {
        'field': 'name',
        'type': 'ordinal',
        'sort': true,
        'axis': {
          'ticks': false,
          'title': '',
        },
      },
      'x': {
        'field': 'value',
        'type': 'quantitative',
        'axis': {
          'ticks': false,
          'orient': 'top',
          'title': unit || 'value',
        },
      },
    },
    'layer': [
      {
        'mark': 'bar'
      }, {
        'mark': {
          'type': 'text',
          'align': 'left',
          'baseline': 'middle',
          'dx': 40,
          'fontSize': 12,
        },
        'encoding': {
          'text': {'field': 'value', 'type': 'quantitative'}
        }
      },
      {
        'mark': {
          'type': 'text',
          'align': 'left',
          'baseline': 'middle',
          'dx': 5,
          'fontSize': 12,
        },
        'encoding': {
          'text': {
            'field': 'percent variation',
            'type': 'quantitative',
            'format': '.0%',
          },
          'color': {
            'condition': {
              'test': 'datum[\'percent variation\'] > 0',
              'value': 'green',
            },
            'value': 'red',
          },
        },
      },
    ],
  }

Note any changes related to sort.

Because the major version didn't change, that says to end users that any improvements must be backwards compatible. It is harder to use a library that unexpectedly breaks like this.

That said, I'm really enjoying the library!

optionally view compiled vega source for vega-lite specs

It would be nice if the viewSource action button could also be set to view the compiled vega source for displays generated with vega-lite. I sometimes use vega-lite to build a rough design and then continue with Vega for the fine-tuning.

Currently, I work around this with the following code, which allows me to put the Vega compiled source underneath the display:

    vg.embed("#vis", my_embed_spec, function(error, result) {
        if (error) throw error; // if there are problems with the file, check the error log        

        // show compiled vega source for vl specifications
        var mycode = d3.select('#source');
        mycode.append('pre')
            .append('code')
            .attr('class', 'json')
            .text(JSON.stringify(result.spec, null, 2));
    });

Error installing npm package (node-gyp)

I get errors trying to add vega-embed to my project on mac osx 10.13 (high sierra)

Anyone have any ideas?

Chads-MBP:kinetix-ui chadbr$ yarn add vega-embed
yarn add v1.0.0
[1/5] 🔍  Validating package.json...
[2/5] 🔍  Resolving packages...
warning [email protected]: 
[3/5] 🚚  Fetching packages...
[4/5] 🔗  Linking dependencies...
warning "@angular/[email protected]" has incorrect peer dependency "@angular/common@^2.2.3".
warning "@angular/[email protected]" has incorrect peer dependency "@angular/core@^2.2.3".
warning "@angular/[email protected]" has incorrect peer dependency "zone.js@^0.7.2".
warning "@ngtools/[email protected]" has incorrect peer dependency "enhanced-resolve@^3.1.0".
warning "@ngtools/[email protected]" has incorrect peer dependency "webpack@^2.2.0 || ^3.0.0".
warning "[email protected]" has incorrect peer dependency "webpack@^2.2.0".
warning "[email protected]" has incorrect peer dependency "webpack@1 || ^2 || ^2.1.0-beta || ^2.2.0-rc || ^3".
warning "[email protected]" has incorrect peer dependency "less@^2.3.1".
warning "[email protected]" has incorrect peer dependency "webpack@^2.0.0 || ^3.0.0".
warning "[email protected]" has incorrect peer dependency "node-sass@^4.0.0".
warning "[email protected]" has incorrect peer dependency "webpack@^2.0.0 || >= 3.0.0-rc.0 || ^3.0.0".
warning "[email protected]" has incorrect peer dependency "stylus@>=0.52.4".
warning "[email protected]" has incorrect peer dependency "file-loader@*".
warning "[email protected]" has incorrect peer dependency "webpack@^1.0.0 || ^2.0.0 || ^3.0.0".
warning "[email protected]" has incorrect peer dependency "webpack@^2.2.0".
warning "[email protected]" has incorrect peer dependency "ajv@>=4.10.0".
[5/5] 📃  Building fresh packages...
[1/2] ⠠ canvas: '-Goutput_dir=.' ]
[2/2] ⠠ canvas-prebuilt: node-pre-gyp http GET https://github.com/chearon/node-canvas-prebuilt/releases/download/v1.6.0/canvas-prebuil
[-/2] ⠠ waiting...
[-/2] ⠠ waiting...
warning Error running install script for optional dependency: "/Users/chadbr/dev/vsts/kinetix-
ui/node_modules/canvas: Command failed.\nExit code: 1\nCommand: node-gyp rebuild\nArguments: 
\nDirectory: /Users/chadbr/dev/vsts/kinetix-ui/node_modules/canvas\nOutput:\ngyp info it worked if 
it ends with ok\ngyp info using [email protected]\ngyp info using [email protected] | darwin | x64\ngyp 
info spawn /Library/Frameworks/Python.framework/Versions/2.7/bin/python2\ngyp info spawn args [ 
'/usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py',\ngyp info spawn args   
'binding.gyp',\ngyp info spawn args   '-f',\ngyp info spawn args   'make',\ngyp info spawn args   '-
I',\ngyp info spawn args   '/Users/chadbr/dev/vsts/kinetix-
ui/node_modules/canvas/build/config.gypi',\ngyp info spawn args   '-I',\ngyp info spawn args   
'/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi',\ngyp info spawn args   '-
I',\ngyp info spawn args   '/Users/chadbr/.node-gyp/8.7.0/include/node/common.gypi',\ngyp info 
spawn args   '-Dlibrary=shared_library',\ngyp info spawn args   '-Dvisibility=default',\ngyp info 
spawn args   '-Dnode_root_dir=/Users/chadbr/.node-gyp/8.7.0',\ngyp info spawn args   '-
Dnode_gyp_dir=/usr/local/lib/node_modules/npm/node_modules/node-gyp',\ngyp info spawn args   
'-Dnode_lib_file=/Users/chadbr/.node-gyp/8.7.0/<(target_arch)/node.lib',\ngyp info spawn args   '-
Dmodule_root_dir=/Users/chadbr/dev/vsts/kinetix-ui/node_modules/canvas',\ngyp info spawn args   
'-Dnode_engine=v8',\ngyp info spawn args   '--depth=.',\ngyp info spawn args   '--no-parallel',\ngyp 
info spawn args   '--generator-output',\ngyp info spawn args   'build',\ngyp info spawn args   '-
Goutput_dir=.' ]\n./util/has_lib.sh: line 31: pkg-config: command not found\ngyp: Call to 
'./util/has_lib.sh freetype' returned exit status 0 while in binding.gyp. while trying to load 
binding.gyp\ngyp ERR! configure error \ngyp ERR! stack Error: `gyp` failed with exit code: 1\ngyp 
ERR! stack     at ChildProcess.onCpExit (/usr/local/lib/node_modules/npm/node_modules/node-
gyp/lib/configure.js:336:16)\ngyp ERR! stack     at emitTwo (events.js:125:13)\ngyp ERR! stack     at 
ChildProcess.emit (events.js:213:7)\ngyp ERR! stack     at Process.ChildProcess._handle.onexit 
(internal/child_process.js:200:12success Saved lockfile.
success Saved 78 new dependencies.
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
└─ [email protected]
✨  Done in 15.24s.
Chads-MBP:kinetix-ui chadbr$ 

Vega Embed has javascript error with Tooltips

I'm using Altair to create html files that use Vega-Embed and hoping to get tooltips working. With versions 3.7 to 3.9 (current) they all throw this error:

JavaScript Error: m.tooltip is not a function. (In 'm.tooltip(g)', 'm.tooltip' is undefined)

Not sure if it's needed but here's the relevant code from Altair's export (with data removed):

  <div id="vis"></div>
  <script type="text/javascript">
	var spec = (excerpted here since it has tons of data.)
    var embed_opt = {"mode": "vega-lite"};

    function showError(el, error){
        el.innerHTML = ('<div class="error">'
                        + '<p>JavaScript Error: ' + error.message + '</p>'
                        + "<p>This usually means there's a typo in your chart specification. "
                        + "See the javascript console for the full traceback.</p>"
                        + '</div>');
        throw error;
    }
    const el = document.getElementById('vis');
    vegaEmbed("#vis", spec, embed_opt)
      .catch(error => showError(el, error));
  </script>

Re-render Vega-embed through Ajax call

Hi,
Couldn't find any related info on this.
I'm using Jquery to have a

re-rendered with an updated Django view that pulls data from a db, feeds this into Altair, which outputs a JSON spec for Vega-Lite, which is fed to a Vega-Embed object on (a portion of) a HTML page.

$.get("a_cp/"+s,
function(response) {
                $('.filtered_resources').html(response);
...

This works perfectly if I the content that needs to be updated is an HTML table. However, if I have a Vega-Embed object, the object will not re-render. I can see in Console that the correct, updated data is loaded into the spec constant.

<div id="viz"></div>
    
  <script>
       
    const spec =  {{ filtered_data|safe }};
    vegaEmbed('#viz', spec, {"mode": "vega-lite", "renderer": "svg", "width": 800, "height": 600, "actions":{export: false, source: false, editor: true} }).catch(console.warn);
    
</script>

I've tried a bunch of suggestions for getting the browser to redraw parts of the interface
$('.filtered_resources').redraw();
but that doesn't seem to work.

Question: is it possible to have the browser re-render the Vega-Embed object?

Tooltip no longer works with more recent versions of vega-embed

<script src="https://cdnjs.cloudflare.com/ajax/libs/vega/3.0.2/vega.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vega-lite/2.0.0-beta.19/vega-lite.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vega-embed/3.0.0-beta.14/vega-embed.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/vega-tooltip/0.4.3/vega-tooltip.min.css"></link>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vega-tooltip/0.4.3/vega-tooltip.min.js"></script>

It is very confusing to try to debug which combination of the modules works. I found that when I changed to vega-emebd/3.0.0-beta.20 my tooltips no longer showed up. Do you have the same issue?

Open in editor breaks if data is not available

Since URLs in Vega or Vega-Lite specs can be relative, the URLs may not be correct. We could either use the origin URL as the baseurl or send the data along when a spec is opened in the editor.

Within vg.embed result.view.width() or .height() can be changed but marks do not appear to reposition

For a Vega specification where height and width have not been specified within the specification itself, the following code causes the marks not to reposition, thus not matching the axes position anymore. I have only observed this behaviour when using vg.embed. With vg.parse, everything works as documented. I should add that I'm rendering the specs in a browser.

var embedSpec = {
    url: vg_spec_url,
    renderer: "svg",
    actions: {export: true, source: true, editor: false}
};

vg.embed("#vis", embedSpec, function(error, result) {
    if (error) throw error;  
    result.view
        .background("white")
        .width(600)
        .height(400)
        .update();
});

should `tooltip` become a configuration property of vega-embed ?

vega-tooltip currently requires the user to manually:

  • extend the vg.embed function;
  • choose between vega-lite and vega flavours;
  • include the additional dependencies (vg-tooltip.js and vg-tooltip.css);
  • create a div container dedicated to the tooltip.

Wouldn't it be much more user-friendly if vg.embed took care of all these steps by providing a tooltip configuration property (boolean or object) and a CSS-stylable vega-tooltip class (similar to the action buttons) ?

More specifically, .tooltip would accept:

  • false (default) for no tooltip;
  • true for tooltip with default options;
  • a vega-tooltip options object for tooltip with provided options.

Support absolute, hardcoded URLs when possible

Currently the links produced for "Open in Vega Editor" cannot be right clicked, etc. I believe in discussions with @domoritz and @kanitw I was told this was because of the limit in possible length of a URL. This number is around 2000 to support most browsers.

Would it break user expectations if we build links and use get parameters when length allows (especially with vega-lite), and failover to the current implement for longer specs?

i18n support of actions

The actions text are hardcoded in English. It would be useful to have the text localized or provide a mechanism for providing localized strings.

add to documentation that the `$schema` property overrides the `mode` option

Suggested wording:

An optional option to parse the spec as one of vega (default) or vega-lite. Please note that if the embedded specification contains the $schema property, Vega-embed will ignore the mode option.

N.B.: Thank you a lot for keeping vega-embed! For the non-IT specialist, this makes things much more convenient.

same `config` object ignored when switching from vega to vega-lite

Here is the javascript code:

const spec1 = "specs/timeline.vg.json";

opt = {"actions":false,
               "renderer": 'svg', "config": SETheme, 
               "padding": {"left": 5, "top": 5, "right": 5, "bottom": 5}
      };

vegaEmbed('#vis', spec1, opt)
    .then(function(result) {
        VIEW = result.view;
        let element = $('div#vis');
        VIEW.width(element.width()).run();
    })
    .catch(console.warn);


$(window).on('resize', function() {
    let element = $('div#vis');
    VIEW.width(element.width()).run();
    })

both timeline.vg.json and timeline.vl.json are copies of this example, in vega's case - compiled by the online editor;

and here is the SETheme object.

Essentially when I switch from timeline.vl.json to timeline.vg.json my config styling drops...

keep the top-level vega(-lite) config block in the (compiled) vega specification

With vega-embed, a top-level vega-lite config block currently disappears from the compiled vega spec and is passed on separately.

Given that the top-level config block takes precedence over external configurations anyway, there does not seem to be any benefit with the current behaviour. What's more, it always removes the config block from result.spec, which is inconvenient in case that the specification is loaded from a json file.

Shouldn't the separate passing on be reserved to a configuration referenced via vega-embed's config parameter, i.e. for external configurations? Alternatively, it would be nice to provide yet another parameter to let the user decide how a top-level config block should be handled by vega-embed.

Also see the discussion here: vega/vega-lite#2333

Missing example of use of RequireJS for vega-embed

Hi,
I would like to dynamically load vega-embed and all its dependencies (vega and vega-lite, which themselves depend on d3, etc.) using the RequireJS library. From previous discussions (see vega/vega#171 among else) I know that vega and D3 are AMD-compatible, so this ought to be doable.

What I am missing is an example of use of vega-embed with RequireJS. The code below throws errors, and I'm not sure if it is due to an incompatibility of vega-embed with RequireJS or my incorrect use or the later library:

requirejs.config({
    paths: {
        d3: "https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.16/d3.min.js?noext",
        d3_geo_projection: "https://cdnjs.cloudflare.com/ajax/libs/d3-geo-projection/0.2.16/d3.geo.projection.min.js?noext",
        d3_layout_cloud: "https://vega.github.io/vega-editor/vendor/d3.layout.cloud.js?noext",
        topojson: "https://cdnjs.cloudflare.com/ajax/libs/topojson/1.6.20/topojson.min.js?noext",
        vg: "https://cdnjs.cloudflare.com/ajax/libs/vega/2.5.1/vega.min.js?noext",
        vl: "https://vega.github.io/vega-lite/vega-lite.js?noext",
        vg_embed: "https://vega.github.io/vega-editor/vendor/vega-embed.js?noext"
    },
    shim: {
        vg_embed: {deps: ["vg", "vl"]},
        vl: {deps: ["vg"]},
        vg: {deps: ["d3", "d3_geo_projection", "d3_layout_cloud", "topojson"]},
        d3_geo_projection: {deps: ["d3"]},
        d3_layout_cloud: {deps: ["d3"]}
    }
});

require(["vg", "vl", "vg_embed"], function(vg, vl, vg_embed) {
    var vg_specification = {
        mode: "vega-lite",
        spec: {
            "description": "A simple bar chart with embedded data.",
            "data": {
                "values": [
                    {"a": "A", "b": 28}, {"a": "B", "b": 55}, {"a": "C", "b": 43},
                    {"a": "D", "b": 91}, {"a": "E", "b": 81}, {"a": "F", "b": 53},
                    {"a": "G", "b": 19}, {"a": "H", "b": 87}, {"a": "I", "b": 52}
                ]
            },
            "mark": "bar",
            "encoding": {
                "x": {"field": "a", "type": "ordinal"},
                "y": {"field": "b", "type": "quantitative"}
            }
        }};

    vg.embed("#vis", vg_specification,
        function (error, chart) {
            chart({el:"#vis"}).update();
        });
});

This throws a TypeError: Cannot read property 'util' of undefined and TypeError: Cannot read property 'embed' of undefined.

Best,
Aurélien

Spec support for animation

It would be useful to also be able to specify animation options as part of an embedding specification.

(And, perhaps all other options that vg.parse.spec takes, as well? That way, you could completely control a standalone vega specification (including passing other data options) via a vega-embed specification.)

Improper error handling for URL load

See embed.js#L25. We currently check for an "error" by seeing if data is undefined. However, that is not how vega-loader works. We should register a .catch(...) method on the returned Promise to print error messages if the Promise fails to resolve.

Error with named data

With a named data source in a vega-lite spec eg "data": {"name": "myData"} vega-embed gives a TypeError: Cannot read property 'length' of null.

vg object is empty

I am not able to load vega. I get errors when using code taken directly from https://vega.github.io/vega-lite/usage/embed.html. This has worked for me in the past, perhaps there was a breaking change. Here is the code I'm using:

<html>
<head>
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="//vega.github.io/vega/vega.js" charset="utf-8"></script>
<script src="//vega.github.io/vega-lite/vega-lite.js" charset="utf-8"></script>
<script src="//vega.github.io/vega-editor/vendor/vega-embed.js" charset="utf-8"></script>
</head>
</html>

something in vega-embed changed and our graphs no longer work and i don't know what it is and it's kind of embarrassing

You can see our embarrassment here:

http://gunrock.github.io/gunrock/doc/latest/md_stats_engines_topc.html

Firefox (for instance) says:

TypeError: (intermediate value).util is undefined[Learn More] (vega-embed.js 181)

which is the JS code

$ = (typeof window !== "undefined" ? window['vg'] : typeof global !== "undefined" ? global['vg'] : null).util.mutator;

Our current includes are:

        <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
        <script src="http://vega.github.io/vega/vega.js" charset="utf-8"></script>
        <script src="http://vega.github.io/vega-lite/vega-lite.js" charset="utf-8"></script>
        <script src="http://vega.github.io/vega-editor/vendor/vega-embed.js" charset="utf-8"></script>

This used to work. I'd appreciate a pointer to how I might fix this. Is there some sort of mailing list or twitter account or web page where y'all announce deployed-code changes that might impact us? This is probably my fault somewhere down the chain, sorry to bug you here.

Issue with clip=True from Altair?

Hi,

I've tried the following Altair code in a Jupyter Lab - Notebook.

chart = alt.Chart(data).mark_bar(clip=True).encode(
    y=alt.Y('name:O', sort= {"op": "mean", "field": "utilization:Q"}),
    x=alt.X('utilization',  scale=alt.Scale(domain=[0,1])),
    color='rank:N',
).to_dict()

This outputs the following JSON:

{'$schema': 'https://vega.github.io/schema/vega-lite/v2.json',
 'config': {'view': {'height': 300, 'width': 400}},
 'data': .....,
 'encoding': {'color': {'field': 'rank', 'type': 'nominal'},
  'x': {'field': 'utilization',
   'scale': {'domain': [0, 1]},
   'type': 'quantitative'},
  'y': {'field': 'name',
   'sort': {'field': 'utilization:Q', 'op': 'mean'},
   'type': 'ordinal'}},
 'mark': {'clip': True, 'type': 'bar'}}

This chart is correctly displayed in Jupyter. However, I have exactly the same code in Python (3.6.4), using Vega-Embed to render my svg.

The browser returns the following error message:
Uncaught ReferenceError: True is not defined

Not sure I fully understand the issue, but should this be a true (lowercase) for Javascript?

Using vega3==0.5.0, vega==0.4.4, altair==2.0.0rc1.

Thank you.

Reset the view

It would be great to have an action to reset the view to the initial state. One option may be to save the state in the beginning and then apply it again when the user wants to reset the chart. I don't know how this interacts with streaming data.

Promise is Error in IE11

I use vega and vega-embed.js older version, it work very well.

I update vega to 3.05 and vega-embed to 3.0.0-beta.19,
an error happend at line 1196 in 3.0.0-beta.19/vega-embed.js.
I found the same error from 3.0.0-beta.19 to 3.0.0-beta.19 22.


function embedMain(el, spec, opt) {
  // Ensure any exceptions will be properly handled
  return new Promise((accept, reject) => {
    embed(el, spec, opt).then(accept, reject);
  });
}

security: custom url sanitizer is not called

I might be mistaken, but I suspect that embed() would call original non-customized vega.loader(). In a hosted scenario, it is highly important to be able to add host-specific url sanitization. For example, I tell Vega to use my own loader here:

https://github.com/nyurik/kibana-vega-vis/blob/3adcb17183e59a6015b63db46aac26528b0d5843/public/vega_view/vega_view.js#L13

But the user effectively bypasses that, by supplying a string instead of a valid json spec.

Updates for vega 3

I went ahead and tested to see if our app was ready for vega 3 by trying out the beta. This package is using a path that doesn't exist any more, require('vega').util.mutator - util is no longer available.

Implicit Dependency on using a CSS loader or Ignoring CSS

Recently our builds started to fail because vega-tooltip is importing css. To get around this, we set up css ignores for the apps that were failing. I'm not sure if this was on purpose. If it is, what are the recommended approaches for loading the CSS?

Admittedly, we're probably going to vendorize your CSS, including it in a styled-jsx tag.

Vega embed instalation

While installing npm, I got errors...I installed Net Framework 2.0 SDK, I still get same errors. Can someone help me with?
image

rc questions / issues

last week I had a setup that looked like this (Angular2 / typescript if it helps):

I copied the vega-embed.d.ts form vega-lite and used it directly:

declare module 'vega-embed' {
  export const config: any;
  export default function embed(e: any, spec: any, ops: any): Promise<any>;
  export const vega: any;
}

Then I used it in a component like so:

import embed from 'vega-embed';
import * as vega from 'vega';

...

  ngOnInit() {
    embed(this.chart.nativeElement, this.spec, { 'actions': false });
  }

with the RC, I removed my vega-embed.d.ts

The 1st problem I ran into I had to include vega-lite in my app or it would fail to compile with a 'vega-lite not defined' -- should it be required?

I added vega-lite, and now I can't get the embed function to compile:

import * as embed from 'vega-embed';
import * as vega from 'vega';

When I try to build -- I get these failures:

ERROR in /Users/chadbr/dev/vsts/kinetix-ui/node_modules/vega-embed/build/embed.d.ts (11,19): Namespace 'vg' has no exported member 'Loader'.

ERROR in /Users/chadbr/dev/vsts/kinetix-ui/src/app/simulation/result/result-chart/result-chart.component.ts (118,5): Cannot invoke an expression whose type lacks a call signature. Type 'typeof "/Users/chadbr/dev/vsts/kinetix-ui/node_modules/vega-embed/build/embed"' has no compatible call signatures.
webpack: Failed to compile.

I've tried a few variations of this -- but clearly I'm missing something simple?

Thanks - Chad

some vega-lite config not respected with vegaEmbed

Not sure if #3 is related, but some vega-lite config allowed with vl.compile(spec,, {config}) are not respected, since line does not compile/PREPROCESSOR using the config. More specifically, the default mark color cannot be changed. Mark fill is populated after compile/preprocess of the vega-lite spec, and the config will not override when vega.parse for runtime in line.

Two workarounds are add config within the vega-lite spec or manually vl.compile(spec, {config}) before passing to vegaEmbed. These workarounds are certainly reasonable options, so I understand if this is just closed and serves as information for other users later.

Example

reproducible example to help explain.

Vega embed broken

It looks like a change in vega or vega-embed.js since yesterday are causing errors.

In particular, here's the error I'm seeing throughout my test suite, which appeared this morning:

        TypeError: undefined is not an object (evaluating '(typeof window !== "undefined" ? window['vg'] : typeof global !== "undefined" ? global['vg'] : null).util.mutator')
             at http://vega.github.io/vega-editor/vendor/vega-embed.js:181
             at http://vega.github.io/vega-editor/vendor/vega-embed.js:364
             at http://vega.github.io/vega-editor/vendor/vega-embed.js:1 in s
             at http://vega.github.io/vega-editor/vendor/vega-embed.js:1
             at http://vega.github.io/vega-editor/vendor/vega-embed.js:6
             at http://vega.github.io/vega-editor/vendor/vega-embed.js:176
             at http://vega.github.io/vega-editor/vendor/vega-embed.js:1 in s
             at http://vega.github.io/vega-editor/vendor/vega-embed.js:1 in e
             at http://vega.github.io/vega-editor/vendor/vega-embed.js:1
             at http://vega.github.io/vega-editor/vendor/vega-embed.js:1

I get an error about vg.embed not being a function when I try to view the vega graphs on my project.

add `scaleFactor` as an option for exporting to SVG and PNG

vega-view's toImageURL() function accepts a scale factor argument. The scale factor argument would be useful in vega-embed to producer higher resolution PNGs. For SVG, it is probably of lesser importance but would still be nice to have.

The argument should be on conditional on the export action. It could be specified either by making action.export an object (e.g. export : { scaleFactor: 5 }) or by adding a separate scaleFactor option. The latter option would likely be less tedious to use.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.