Skip to content

Instantly share code, notes, and snippets.

@EE2dev
Last active August 18, 2020 22:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EE2dev/e9898f7471511ddf68858ef2ef23c243 to your computer and use it in GitHub Desktop.
Save EE2dev/e9898f7471511ddf68858ef2ef23c243 to your computer and use it in GitHub Desktop.
vega-lite API example: cross-filter
license: mit

Converted from : https://observablehq.com/@vega/vega-lite-cross-filter-example?collection=@vega/vega-lite-api

A very simple example of how to run the wonderful JavaScript API for vega-lite directly in the browser. This one uses vegaEmbed to render the chart. The key is to use the api to generate the spec, and then vegaEmbed to render it.

Built with blockbuilder.org

forked from john-guerra's block: vega-lite JavaScript API browser example

forked from john-guerra's block: vega-lite JavaScript API browser example with vegaEmbed

forked from EE2dev's block: vega-lite JavaScript API browser example with vegaEmbed

forked from EE2dev's block: vega-lite JavaScript API browser example with vegaEmbed

forked from EE2dev's block: vega-lite API example: cross-filter

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<div id="chart"></div>
<script src="https://cdn.jsdelivr.net/npm/vega@5.7.2"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-lite@4.0.0-beta.10"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-embed@5.1.3"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-lite-api@0.1.0"></script>
<script>
// create one interval brush for each histogram
const brushDelay = vl.selectInterval('delay').encodings('x');
const brushDist = vl.selectInterval('dist').encodings('x');
const brushTime = vl.selectInterval('time').encodings('x');
// function that creates a histogram visualization
function hist(field, brush, crossfilter) {
// binned x-axis encoding
const x = vl.x()
.fieldQ(field)
.bin({maxbins: 100, minstep: 1})
.axis({title: field, titleAnchor: 'start', format: 'd'});
return vl.layer(
// transparent base layer with unfiltered data
vl.markBar().select(brush)
.encode(x, vl.color().value('transparent')),
// cross-filtered histogram bars
vl.markBar().transform(vl.filter(crossfilter))
.encode(x, vl.y().count().axis(null))
)
.width(900)
.height(100);
}
// vconcat three cross-filtered histograms
const chartSpec = vl.vconcat(
hist('delay', brushDelay, vl.and(brushDist, brushTime)),
hist('distance', brushDist, vl.and(brushDelay, brushTime)),
hist('time', brushTime, vl.and(brushDelay, brushDist))
)
.data('https://cdn.jsdelivr.net/npm/vega-datasets@1/data/flights-5k.json')
.transform(vl.calculate('hours(datum.date) + minutes(datum.date) / 60').as('time'))
.config({view: {stroke: null}})
.toJSON();
vegaEmbed("#chart", chartSpec);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment