Skip to content

Instantly share code, notes, and snippets.

@betafcc
Last active November 18, 2018 13:45
Show Gist options
  • Save betafcc/9eb6fa7f2f43bae71dc07b833499f7d0 to your computer and use it in GitHub Desktop.
Save betafcc/9eb6fa7f2f43bae71dc07b833499f7d0 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Vega Lite pie chart</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/vega-embed/3.23.1/vega-embed.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vega/4.3.0/vega.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vega-lite/2.6.0/vega-lite.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vega-embed/3.23.1/vega-embed.min.js"></script>
</head>
<body>
<div id="vis"></div>
<script src="util.js"></script>
<script>
const data = [{"A": 1}, {"A": 2}, {"A": 3}, {"A": 4}, {"A": 5}]
const values = features({data, column: 'A'})
const spec = {
data: {values},
mark: 'geoshape',
projection: {type: 'azimuthalEquidistant', rotate: [0, 90, 0]},
encoding: {
color: {field: 'A', type: 'nominal'},
tooltip: [{field: 'A', type: 'nominal'}],
}
}
vegaEmbed('#vis', spec, {defaultStyle: true})
</script>
</body>
</html>
const features = ({data: [...rows], column}) =>
geometries(rows.map(r => r[column]))
.map((el, i) => ({
...rows[i],
type: 'Feature',
geometry: el
}))
const geometries = ([...xs]) =>
xs
// map to angles
.map(linearScale({
domain: [0, xs.reduce((a, b) => a + b)],
range: [0, 360],
}))
// cumulative sum
.reduce((acc, n, i) => acc.concat(acc[i] + n), [0])
// take pairs
.reduce((acc, n, i, arr) => [...acc, [arr[i - 1], n]], []).slice(1)
// to geojson geometry
.map(([startAngle, endAngle]) => ({
type: 'Polygon',
coordinates: [[
[0, 90],
[endAngle, -89],
[startAngle, -89],
[0, 90],
]]
}))
const linearScale = ({domain: [xi, xf], range: [yi, yf]}) => {
const a = (yi - yf) / (xi - xf)
const b = yi - a * xi
return x => a * x + b
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment