Published
Edited
Oct 16, 2019
Insert cell
md`# Vega Lite Tutorial, Part 2`
Insert cell
import {vl} from "@vega/vega-lite-api"
Insert cell
import {printTable} from "@uwdata/data-utilities"
Insert cell
data = require('vega-datasets')
Insert cell
//gapminderData = data['gapminder.json']()
Insert cell
gapminderData = (await require('vega-datasets'))['gapminder.json']()
Insert cell
printTable(gapminderData.slice(0,10))
Insert cell
data2000 = gapminderData.filter(d => d.year === 2000)
Insert cell
printTable(data2000.slice(0,10))
Insert cell
vl.markPoint({filled: true})
.data(data2000)
.encode(
vl.x().fieldQ('fertility').scale({zero: false}),
vl.y().fieldQ('life_expect').scale({zero: false}),
vl.size().fieldQ('pop').scale({range: [0, 1000]}).legend({orient: 'bottom', titleOrient: 'left'}),
vl.color().fieldN('cluster').legend(null),
vl.opacity().value(0.5),
// vl.tooltip().fieldN('country'),
vl.order().fieldQ('pop').sort('descending'),
vl.tooltip(['country', 'fertility', 'life_expect']), // how do you overwrite tooltips? add later.
vl.column().fieldN('cluster')
)
.width(130)
.height(130)
.render()
Insert cell
vl.markBar()
.data(data2000)
.encode(
vl.y().fieldQ('pop'),
vl.x().fieldN('cluster'),
vl.color().fieldN('country').legend(null)
// vl.opacity().value(0.25)
//vl.shape().fieldN('cluster')
)
.title("Bad colors for countriese")
.render()
Insert cell
md`Data comes from http://bit.ly/new-poll`
Insert cell
d3 = require('d3')
Insert cell
trumpdata = d3.csv("https://docs.google.com/spreadsheets/d/e/2PACX-1vTIt9s4FIQ1Cr6fPZiK7rDeDY3QrarYSko2JGrwVgorZHzu2JvDh1O938v23dz5KfE56e6Nk0LYrDjp/pub?gid=1380040337&single=true&output=csv")
Insert cell
printTable(trumpdata.slice(0,10))
Insert cell
trumpAllVoters = trumpdata.filter(d => d.subgroup === "All polls")
Insert cell
printTable(trumpAllVoters.slice(0,10))
Insert cell
{
const approval = vl.markArea({color: '#009f29', opacity: 0.25})
.data(trumpAllVoters)
.encode(
vl.x().fieldT('modeldate'),
vl.y().fieldQ('approve_lo'),
vl.y2().fieldQ('approve_hi')
)
const disapproval = vl.markArea({color: '#ff7400', opacity: 0.25})
.data(trumpAllVoters)
.encode(
vl.x().fieldT('modeldate'),
vl.y().fieldQ('disapprove_lo'),
vl.y2().fieldQ('disapprove_hi')
)
const approvalLine = vl.markLine({color: '#009f29'})
.data(trumpAllVoters)
.encode(
vl.x().fieldT('modeldate'),
vl.y().fieldQ('approve_estimate')
)

const disapprovalLine = vl.markLine({color: '#ff7400'})
.data(trumpAllVoters)
.encode(
vl.x().fieldT('modeldate'),
vl.y().fieldQ('disapprove_estimate')
)

return vl.layer(approvalLine, disapprovalLine, approval, disapproval).render()

}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more