data visualisation

sketchnotes/zines

linux

Viz Playground - basic data viz with Vega

Oh no :-/ I haven’t written a post in so long!

For my second technical post, I had in mind something related to the talk I gave at PyCon Sweden 2017 back in September 2017 (here’s a link to my slides on Github).
My idea then was to share my experience of trying a new data visualisation tool. This tool called Altair isn’t another data visualisation library as such, but a Python API to access the powerful and simple Vega-LiteJSON like grammar for interactive graphics (itself build on top of Vega).

Why Vega?

While it was fun and interesting to try out Altair (I used it for a personal project), it is still in the process of supporting Vega-Lite 2.0. So, I now decided to directly try out Vega.

The idea is still to have a go-to tool for creating a rapid data visualisation. Specific use cases would be a prototype, a hackathon project… Come on, don’t tell me you don’t have a dataset of interest to visualise and share with a colleague or the world (well, your Twitter followers at least)!

Vega generates web visualisation using either HTML5 Canvas or SVG. And here we’re working with Vega-Lite which provides a more concise syntax than Vega.

Create a Vega-Lite chart

Vega-Lite visualisations are specified by JSON objects that can contain several properties like “name”, “description”, “title”, “data”, “transform”, etc…

To define a minimal chart you want to provide the “data”, “mark” and “encoding” properties.

The data source is expected to be tabular data. It can be inline data (see below) or loaded from a file (JSON, CSV or TSV). [1]

The mark is the type of visualisation you need, in this case “bar” for a bar chart. It can be a simple string or a mark object. [2]

The encoding property links the data fields and the axis of the chart. In our case we’re creating an horizontal bar chart, so we’re inverting “x” and “y”. Here the “y” axis will display the “element” which is an “ordinal” data type as I’m using it as a label for each data point and want to keep the order. And the “x” axis will display the actual “value” field hence the type is “quantitative”.
The encoding can have more properties to transform the data. [3]

2) Add a div where the visualisation will be attached <div id="vis"></div>.

3) Link the #vis div to the Vega-Lite chart object using the function vegaEmbed(), like this: vegaEmbed("#vis", chart);.

The chart object to be embedded contains “data”, “mark” and “encoding” properties as well as an optional JSON schema, “$schema”, and an optional “description”.

In my example below you can see the vegaEmbed function can take an extra optional property (called opt below). This gives you more control on the rendering of the visualisation.
Here I choose to render a SVG (instead of a PNG image) and I specify its size.