Vega Graph Spec Tutorial - US presidents

Mikanebu

Files Size Format Created Updated License Source
3 9kB csv zip 3 weeks ago vega-datasets
This is an example dataset, that demonstrates how to build visualizations using the "Vega Graph Spec". We are using lifelines of the first 5 presidents of the US - one of the examples from vega editor - and displaying it here, on DataHub with small modifications in vega-spec. Views We assume that read more
Download

Data Files

File Description Size Last changed Download Other formats
people [csv] 376B people [csv] people [json] (376B)
events [csv] 134B events [csv] events [json] (134B)
vega-views-tutorial-lines_zip [zip] Compressed versions of dataset. Includes normalized CSV and JSON data with original data and datapackage.json. 3kB vega-views-tutorial-lines_zip [zip]

people  

This is a preview version. There might be more data in the original version.

Field information

Field Name Order Type (Format) Description
label 1 string
born 2 number
died 3 number
enter 4 number
leave 5 number

events  

This is a preview version. There might be more data in the original version.

Field information

Field Name Order Type (Format) Description
name 1 string
when 2 date (%Y-%m-%d)

vega-views-tutorial-lines_zip  

This is a preview version. There might be more data in the original version.

Read me

This is an example dataset, that demonstrates how to build visualizations using the “Vega Graph Spec”. We are using lifelines of the first 5 presidents of the US - one of the examples from vega editor - and displaying it here, on DataHub with small modifications in vega-spec.

Views

We assume that you are familiar with what datapackage.json is and its specifications.

To create graphs for your tabular data, the datapackage.json should include the views attribute that is used for visualizations.

If you are familiar with Vega specifications, you probably would like to use all its features. To use it, inside views you should set specType to "vega" and define some graph specifications in spec property. See below for more details.

Vega Graph Specifications

This is the views property that is used for this page:

{
  ...,
  "views": [
    {
      "name": "demo-datapackage-vega",
      "title": "Lifelines of first 5 US presidents",
      "resources": ["people", "events"],
      "specType": "vega",
      "spec": {
        "width": 800,
        "height": 200,
        "data": [
          {
            "name": "people"
          },
          {
            "name": "events",
            "format": {"type":"json", "parse":{"when":"date"}}
          }
        ],
        "scales": [
          {
            "name": "y",
            "type": "ordinal",
            "range": "height",
            "domain": {"data": "people", "field": "label"}
          },
          {
            "name": "x",
            "type": "time",
            "range": "width",
            "round": true,
            "nice": "year",
            "domain": {"data": "people", "field": ["born", "died"]}
          }
        ],
        "axes": [
          {"type": "x", "scale": "x"}
        ],
        "marks": [
          {
            "type": "text",
            "from": {"data": "events"},
            "properties": {
              "enter": {
                "x": {"scale": "x", "field": "when"},
                "y": {"value": -10},
                "angle": {"value": -25},
                "fill": {"value": "#000"},
                "text": {"field": "name"},
                "font": {"value": "Helvetica Neue"},
                "fontSize": {"value": 10}
              }
            }
          },
          {
            "type": "rect",
            "from": {"data": "events"},
            "properties": {
              "enter": {
                "x": {"scale": "x", "field": "when"},
                "y": {"value": -8},
                "width": {"value": 1},
                "height": {"field": {"group": "height"}, "offset": 8},
                "fill": {"value": "#888"}
              }
            }
          },
          {
            "type": "text",
            "from": {"data": "people"},
            "properties": {
              "enter": {
                "x": {"scale": "x", "field": "born"},
                "y": {"scale": "y", "field": "label", "offset": -3},
                "fill": {"value": "#000"},
                "text": {"field": "label"},
                "font": {"value": "Helvetica Neue"},
                "fontSize": {"value": 10}
              }
            }
          },
          {
            "type": "rect",
            "from": {"data": "people"},
            "properties": {
              "enter": {
                "x": {"scale": "x", "field": "born"},
                "x2": {"scale": "x", "field": "died"},
                "y": {"scale": "y", "field": "label"},
                "height": {"value": 2},
                "fill": {"value": "#557"}
              }
            }
          },
          {
            "type": "rect",
            "from": {"data": "people"},
            "properties": {
              "enter": {
                "x": {"scale": "x", "field": "enter"},
                "x2": {"scale": "x", "field": "leave"},
                "y": {"scale": "y", "field": "label", "offset":-1},
                "height": {"value": 4},
                "fill": {"value": "#e44"}
              }
            }
          }
        ]
      }
    }
  ]
}

You can use almost the same specifications inside spec attribute, that are used for setting the Vega graphs. Only difference is that in data property, url and path attributes are moved out. Instead we use name attribute to reference to a resource. Note, how we created a new object inside data property - {"name": "flights-airport"} to reference it to a resource (this names are identical to names of resources):

  ...
  "spec": {
    ...
    "data": [
      {
        "name": "people"
      },
      {
        "name": "events",
        ...
      }
    ],
  }

Outside of spec attribute there are some other important parameters to note:

Attribute Type Description
name String Unique identifier for view within list of views.
title String Title for the graph.
resources Array Data sources for this spec. It can be either resource name or index. By default it is the first resource.
specType String Available options: simple, vega, plotly (Required).

Import into your tool

In order to use Data Package in R follow instructions below:

install.packages("devtools")
library(devtools)
install_github("hadley/readr")
install_github("ropenscilabs/jsonvalidate")
install_github("ropenscilabs/datapkg")

#Load client
library(datapkg)

#Get Data Package
datapackage <- datapkg_read("https://pkgstore.datahub.io/b6c7c7180404aeb2863e592a9a72deb9/vega-views-tutorial-lines/latest")

#Package info
print(datapackage)

#Open actual data in RStudio Viewer
View(datapackage$data$"people")
View(datapackage$data$"events")
View(datapackage$data$"vega-views-tutorial-lines_zip")

Tested with Python 3.5.2

To generate Pandas data frames based on JSON Table Schema descriptors we have to install jsontableschema-pandas plugin. To load resources from a data package as Pandas data frames use datapackage.push_datapackage function. Storage works as a container for Pandas data frames.

In order to work with Data Packages in Pandas you need to install our packages:

$ pip install datapackage
$ pip install jsontableschema-pandas

To get Data Package run following code:

import datapackage

data_url = "https://pkgstore.datahub.io/b6c7c7180404aeb2863e592a9a72deb9/vega-views-tutorial-lines/latest/datapackage.json"

# to load Data Package into storage
storage = datapackage.push_datapackage(data_url, 'pandas')

# to see datasets in this package
storage.buckets

# you can access datasets inside storage, e.g. the first one:
storage[storage.buckets[0]]

In order to work with Data Packages in Python you need to install our packages:

$ pip install datapackage

To get Data Package into your Python environment, run following code:

import datapackage

dp = datapackage.DataPackage('https://pkgstore.datahub.io/b6c7c7180404aeb2863e592a9a72deb9/vega-views-tutorial-lines/latest/datapackage.json')

# see metadata
print(dp.descriptor)

# get list of csv files
csvList = [dp.resources[x].descriptor['name'] for x in range(0,len(dp.resources))]
print(csvList) # ["resource name", ...]

# access csv file by the index starting 0
print(dp.resources[0].data)

To use this dataset in JavaScript, please, follow instructions below:

Install data.js module using npm:

  $ npm install data.js

Once the package is installed, use code snippet below:

  const {Dataset} = require('data.js')

  const path = 'https://pkgstore.datahub.io/b6c7c7180404aeb2863e592a9a72deb9/vega-views-tutorial-lines/latest/datapackage.json'

  const dataset = Dataset.load(path)

  // get a data file in this dataset
  const file = dataset.resources[0]
  const data = file.stream()

In order to work with Data Packages in SQL you need to install our packages:

$ pip install datapackage
$ pip install jsontableschema-sql
$ pip install sqlalchemy

To import Data Package to your SQLite Database, run following code:

import datapackage
from sqlalchemy import create_engine

data_url = 'https://pkgstore.datahub.io/b6c7c7180404aeb2863e592a9a72deb9/vega-views-tutorial-lines/latest/datapackage.json'
engine = create_engine('sqlite:///:memory:')

# to load Data Package into storage
storage = datapackage.push_datapackage(data_url, 'sql', engine=engine)

# to see datasets in this package
storage.buckets

# to execute sql command (assuming data is in "data" folder, name of resource is data and file name is data.csv)
storage._Storage__connection.execute('select * from data__data___data limit 1;').fetchall()

# description of the table columns
storage.describe('data__data___data')
Datapackage.json