Skip to content

Instantly share code, notes, and snippets.

@EE2dev
Last active August 18, 2020 22:00
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/9e9bf25ead1d3d71fae033ca177ce9a9 to your computer and use it in GitHub Desktop.
Save EE2dev/9e9bf25ead1d3d71fae033ca177ce9a9 to your computer and use it in GitHub Desktop.
vega-lite JavaScript API browser example with vegaEmbed
license: mit

Converted from : https://observablehq.com/@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

<!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>
const width = 900;
const brush = vl.selectInterval().encodings('x');
const click = vl.selectMulti().encodings('color');
const scale = {
domain: ['sun', 'fog', 'drizzle', 'rain', 'snow'],
range: ['#e7ba52', '#a7a7a7', '#aec7e8', '#1f77b4', '#9467bd']
};
const plot1 = vl.markPoint({filled: true})
.encode(
vl.color().value('lightgray')
.if(brush, vl.color().fieldN('weather').scale(scale).title('Weather')),
vl.size().fieldQ('precipitation').scale({domain: [-1, 50], range: [10, 500]}).title('Precipitation'),
vl.order().fieldQ('precipitation').sort('descending'),
vl.x().timeMD('date').axis({title: 'Date', format: '%b'}),
vl.y().fieldQ('temp_max').scale({domain: [-5, 40]}).axis({title: 'Maximum Daily Temperature (°C)'})
)
.width(width)
.height(300)
.select(brush)
.transform(vl.filter(click));
const plot2 = vl.markBar()
.encode(
vl.color().value('lightgray')
.if(click, vl.color().fieldN('weather').scale(scale).title('Weather')),
vl.x().count(),
vl.y().fieldN('weather').scale({domain: scale.domain}).title('Weather')
)
.width(width)
.select(click)
.transform(vl.filter(brush));
const chartSpec = vl.vconcat(plot1, plot2)
.data('https://cdn.jsdelivr.net/npm/vega-datasets@1/data/seattle-weather.csv')
.autosize({type: 'fit-x', contains: 'padding'})
.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