- Reproduce penguins scatterplot with Vega
September 20, 2022
<!DOCTYPE html>
<html lang="en">
<head>
<title>CSC 444 First Vega Plot</title>
<meta charset="UTF-8" />
<script src="https://vega.github.io/vega/vega.min.js"></script>
</head>
<body>
<div id="view"></div>
</body>
<script src="source/penguins.js"></script>
</html>
In your penguins.js you already have some code that sets up a new vega View (based on the #view div in index.html).
// create runtime
var runtime = vega.parse(spec);
// create view
var view = new vega.View(runtime)
.renderer("svg")
.initialize("#view")
.hover();
// run it
view.run();
For our spec we define what our visualization will look like.
Let’s start with width and height of our svg (and some padding)
var spec = {
width: 500,
height: 500,
padding: 50
}
Note how the spec object is an object like we’ve seen before, with property: value syntax.
I have the penguins data in json format on GitHub for us to use.
data: [
{
url: "https://raw.githubusercontent.com/picoral/csc-444-data/main/penguins.json",
name: "penguins"
}
]
Scales use the same concepts as d3:
type can be linear, ordinal, etc.domain and a rangewidthname so you can call it later in your specscales: [
{
name: "xScale",
type: "linear",
domain: {data: "penguins", field: "billLength"},
range: "width"
}
]
To draw on the svg using the data observations, we do what we did for d3, but in an object format:
marks: [
{
type: "symbol",
from: { data: "penguins" },
encode: {
enter: {
x: { field: "billLength", scale: "xScale" },
y: { field: "billDepth", scale: "yScale" },
}
}
}
]
For adding axes, we need to specify the scale and the orientation.
axes: [
{
scale: "xScale",
orient: "bottom",
}
]
scalesmarks with the fill propertyCheck the Vega documentation on scales for help.
legends property to the speclegends with your color scale mapped to fillCheck the Vega documentation on legends
title property to your spec with an object that specifies a string for text, subtitle, fontSize, and any other property you can find in the documentation