Vega Graph Spec Tutorial - US presidents

examples

Files Size Format Created Updated License Source
3 69kB csv zip 6 years 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 Developers

Data Files

Download files in this dataset

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

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)

Integrate this dataset into your favourite tool

Use our data-cli tool designed for data wranglers:

data get https://datahub.io/examples/vega-views-tutorial-lines
data info examples/vega-views-tutorial-lines
tree examples/vega-views-tutorial-lines
# Get a list of dataset's resources
curl -L -s https://datahub.io/examples/vega-views-tutorial-lines/datapackage.json | grep path

# Get resources

curl -L https://datahub.io/examples/vega-views-tutorial-lines/r/0.csv

curl -L https://datahub.io/examples/vega-views-tutorial-lines/r/1.csv

curl -L https://datahub.io/examples/vega-views-tutorial-lines/r/2.zip

If you are using R here's how to get the data you want quickly loaded:

install.packages("jsonlite", repos="https://cran.rstudio.com/")
library("jsonlite")

json_file <- 'https://datahub.io/examples/vega-views-tutorial-lines/datapackage.json'
json_data <- fromJSON(paste(readLines(json_file), collapse=""))

# get list of all resources:
print(json_data$resources$name)

# print all tabular data(if exists any)
for(i in 1:length(json_data$resources$datahub$type)){
  if(json_data$resources$datahub$type[i]=='derived/csv'){
    path_to_file = json_data$resources$path[i]
    data <- read.csv(url(path_to_file))
    print(data)
  }
}

Note: You might need to run the script with root permissions if you are running on Linux machine

Install the Frictionless Data data package library and the pandas itself:

pip install datapackage
pip install pandas

Now you can use the datapackage in the Pandas:

import datapackage
import pandas as pd

data_url = 'https://datahub.io/examples/vega-views-tutorial-lines/datapackage.json'

# to load Data Package into storage
package = datapackage.Package(data_url)

# to load only tabular data
resources = package.resources
for resource in resources:
    if resource.tabular:
        data = pd.read_csv(resource.descriptor['path'])
        print (data)

For Python, first install the `datapackage` library (all the datasets on DataHub are Data Packages):

pip install datapackage

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

from datapackage import Package

package = Package('https://datahub.io/examples/vega-views-tutorial-lines/datapackage.json')

# print list of all resources:
print(package.resource_names)

# print processed tabular data (if exists any)
for resource in package.resources:
    if resource.descriptor['datahub']['type'] == 'derived/csv':
        print(resource.read())

If you are using JavaScript, please, follow instructions below:

Install data.js module using npm:

  $ npm install data.js

Once the package is installed, use the following code snippet:

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

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

// We're using self-invoking function here as we want to use async-await syntax:
;(async () => {
  const dataset = await Dataset.load(path)
  // get list of all resources:
  for (const id in dataset.resources) {
    console.log(dataset.resources[id]._descriptor.name)
  }
  // get all tabular data(if exists any)
  for (const id in dataset.resources) {
    if (dataset.resources[id]._descriptor.format === "csv") {
      const file = dataset.resources[id]
      // Get a raw stream
      const stream = await file.stream()
      // entire file as a buffer (be careful with large files!)
      const buffer = await file.buffer
      // print data
      stream.pipe(process.stdout)
    }
  }
})()

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": {
        "$schema": "https://vega.github.io/schema/vega/v3.0.json",
        "width": 800,
        "height": 200,
        "padding": 5,
        "data": [
          {
            "name": "people"
          },
          {
            "name": "events",
            "format": {
              "type": "json",
              "parse": {
                "when": "date"
              }
            }
          }
        ],
        "scales": [
          {
            "name": "yscale",
            "type": "band",
            "range": [
              0,
              {
                "signal": "height"
              }
            ],
            "domain": {
              "data": "people",
              "field": "label"
            }
          },
          {
            "name": "xscale",
            "type": "time",
            "range": "width",
            "round": true,
            "domain": {
              "data": "people",
              "fields": [
                "born",
                "died"
              ]
            }
          }
        ],
        "axes": [
          {
            "orient": "bottom",
            "scale": "xscale"
          }
        ],
        "marks": [
          {
            "type": "text",
            "from": {
              "data": "events"
            },
            "encode": {
              "enter": {
                "x": {
                  "scale": "xscale",
                  "field": "when"
                },
                "y": {
                  "value": -10
                },
                "angle": {
                  "value": -25
                },
                "fill": {
                  "value": "#000"
                },
                "text": {
                  "field": "name"
                },
                "fontSize": {
                  "value": 10
                }
              }
            }
          },
          {
            "type": "rect",
            "from": {
              "data": "events"
            },
            "encode": {
              "enter": {
                "x": {
                  "scale": "xscale",
                  "field": "when"
                },
                "y": {
                  "value": -8
                },
                "width": {
                  "value": 1
                },
                "height": {
                  "field": {
                    "group": "height"
                  },
                  "offset": 8
                },
                "fill": {
                  "value": "#888"
                }
              }
            }
          },
          {
            "type": "text",
            "from": {
              "data": "people"
            },
            "encode": {
              "enter": {
                "x": {
                  "scale": "xscale",
                  "field": "born"
                },
                "y": {
                  "scale": "yscale",
                  "field": "label",
                  "offset": -3
                },
                "fill": {
                  "value": "#000"
                },
                "text": {
                  "field": "label"
                },
                "fontSize": {
                  "value": 10
                }
              }
            }
          },
          {
            "type": "rect",
            "from": {
              "data": "people"
            },
            "encode": {
              "enter": {
                "x": {
                  "scale": "xscale",
                  "field": "born"
                },
                "x2": {
                  "scale": "xscale",
                  "field": "died"
                },
                "y": {
                  "scale": "yscale",
                  "field": "label"
                },
                "height": {
                  "value": 2
                },
                "fill": {
                  "value": "#557"
                }
              }
            }
          },
          {
            "type": "rect",
            "from": {
              "data": "people"
            },
            "encode": {
              "enter": {
                "x": {
                  "scale": "xscale",
                  "field": "enter"
                },
                "x2": {
                  "scale": "xscale",
                  "field": "leave"
                },
                "y": {
                  "scale": "yscale",
                  "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).
Datapackage.json