Simple Graph Spec Tutorial

examples

Files Size Format Created Updated License Source
1 41kB csv CBOE VIX Page
This is an example Data Package, that demonstrates how to build the simple and nice graphs using the "Simple Graph Spec". We are using CBOE Volatility Index (VIX) time-series dataset for 2015-2016 as an example to create line and bar charts. Views We assume that you are familiar with what read more
Download

Data Files

vix-daily  

Field information

Field Name Order Type (Format) Description
Date 1 date (fmt:%Y-%m-%d)
VIXOpen 2 number
VIXHigh 3 number
VIXLow 4 number
VIXClose 5 number

Read me

This is an example Data Package, that demonstrates how to build the simple and nice graphs using the "Simple Graph Spec". We are using CBOE Volatility Index (VIX) time-series dataset for 2015-2016 as an example to create line and bar charts.

Views

We assume that you are familiar with what datapackage.json is and it's specifications.

To create graphs for your tabular Data Package, the datapackage.json should include the views attribute that is responsible for visualizations.

"Simple Graph Spec" is the quickest and easiest way to build a graph . To use it, inside views you should set specType to "simple" and define some graph specifications in spec. See example datapackage.json:

{
  "datahub": {
    "findability": "published",
    "hash": "61171608fac43bd4de4fac0ea84702d1",
    "modified": "2017-08-08T17:38:18.828111",
    "owner": "examples",
    "ownerid": "examples",
    "stats": {
      "bytes": 42102,
      "rowcount": 644
    }
  },
  "id": "examples/simple-graph-spec",
  "name": "simple-graph-spec",
  "readme": "This is an example Data Package, that demonstrates how to build the simple and nice graphs using the \"Simple Graph Spec\". We are using CBOE Volatility Index (VIX) time-series dataset for 2015-2016 as an example to create line and bar charts.\n\n## Views\n\nWe assume that you are familiar with what [datapackage.json][datapackage.json] is and it's specifications.\n\nTo create graphs for your tabular Data Package, the `datapackage.json` should include the `views` attribute that is responsible for visualizations.\n\n\"Simple Graph Spec\" is the quickest and easiest way to build a graph . To use it, inside `views` you should set `specType` to \"simple\" and define some graph specifications in `spec`. See example datapackage.json:\n\n{{ datapackage.json }}\n\n<br>\n\ninside `spec` attribute, there are only 3 properties enough to define graph specifications:\n\n<table class=\"table table-bordered table-striped resource-summary\">\n  <thead>\n   <tr>\n     <th>Attribute</th>\n     <th>Type</th>\n     <th>Description</th>\n   </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>type</th>\n      <td>String</td>\n      <td>line, bar, pie (defaults to line)</td>\n    </tr>\n    <tr>\n      <th>group</th>\n      <td>String</td>\n      <td>Field name, that will be used as abscissa (usually date field)</td>\n    </tr>\n    <tr>\n      <th>series</th>\n      <td>Array</td>\n      <td>Field name(s) that will be used as ordinate</td>\n    </tr>\n  </tbody>\n</table>\n\nYou can define multiple views for your Data Package. For example, to display line graph as presented above, we defined graph `type` to be a `line`\n\n```\n  ...\n  \"spec\": {\n    \"type\": \"line\",\n    ...\n  }\n```\n\nSimilarly to display bar chart we've used `bar` type.\n\n```\n  ...\n  \"spec\": {\n    \"type\": \"bar\",\n    ...\n  }\n```\n\nWe use `Date` field to display data over time, by setting `group` attribute to the field name\n\n```\n  ...\n  \"spec\": {\n    ...\n    \"group\": \"Date\",\n    ...\n  }\n```\n\nYou can set any number of fields to display in `series` attribute as an array\n\n```\n  ...\n  \"spec\": {\n    ...\n    \"series\": [\n      \"VIXHigh\",\n      \"VIXLow\"\n    ]\n }\n```\n\nIn our case we've displayed line graph for `VIXHigh` and `VIXLow` and similarly, in the bar chart, we use all four series and all of them are presented in chart.\n\nOutside of `spec` attribute there are some other important parameters to note:\n\n<table class=\"table table-bordered table-striped resource-summary\">\n  <thead>\n   <tr>\n     <th>Attribute</th>\n     <th>Type</th>\n     <th>Description</th>\n   </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>name</th>\n      <td>String</td>\n      <td>Unique identifier for view within list of views (lines 51 and 62)</td>\n    </tr>\n    <tr>\n      <th>title</th>\n      <td>String</td>\n      <td>Title for the graph (lines 52 and 63)</td>\n    </tr>\n    <tr>\n      <th>resources</th>\n      <td>Array</td>\n      <td>Data sources for this spec. It can be either resource name or index. By default it is the first resource (lines 53 and 64)</td>\n    </tr>\n    <tr>\n      <th>specType</th>\n      <td>String</td>\n      <td>Available options: simple, vega, plotly <strong>(Required)</strong></td>\n    </tr>\n  </tbody>\n</table>\n\n[datapackage.json]: http://specs.frictionlessdata.io/data-package/#specification\n",
  "resources": [
    {
      "bytes": 11630,
      "datahub": {
        "derivedFrom": [
          "vix-daily"
        ],
        "type": "derived/csv"
      },
      "dialect": {
        "delimiter": ",",
        "doubleQuote": true,
        "lineTerminator": "\r\n",
        "quoteChar": "\"",
        "skipInitialSpace": false
      },
      "encoding": "utf-8",
      "format": "csv",
      "hash": "e340e16a7d5892ff193d15291eb46c95",
      "mediatype": "text/csv",
      "name": "vix-daily",
      "path": "data/csv/data/vix-daily.csv",
      "rowcount": 322,
      "schema": {
        "fields": [
          {
            "description": "",
            "format": "fmt:%Y-%m-%d",
            "name": "Date",
            "type": "date"
          },
          {
            "decimalChar": ".",
            "description": "",
            "groupChar": "",
            "name": "VIXOpen",
            "type": "number"
          },
          {
            "decimalChar": ".",
            "description": "",
            "groupChar": "",
            "name": "VIXHigh",
            "type": "number"
          },
          {
            "decimalChar": ".",
            "description": "",
            "groupChar": "",
            "name": "VIXLow",
            "type": "number"
          },
          {
            "decimalChar": ".",
            "description": "",
            "groupChar": "",
            "name": "VIXClose",
            "type": "number"
          }
        ],
        "primaryKey": "Date"
      },
      "title": "",
      "description": "",
      "alternates": [
        {
          "datahub": {
            "type": "source/tabular"
          },
          "format": "csv",
          "mediatype": "text/csv",
          "name": "vix-daily",
          "schema": {
            "fields": [
              {
                "description": "",
                "format": "any",
                "name": "Date",
                "type": "date"
              },
              {
                "description": "",
                "name": "VIXOpen",
                "type": "number"
              },
              {
                "description": "",
                "name": "VIXHigh",
                "type": "number"
              },
              {
                "description": "",
                "name": "VIXLow",
                "type": "number"
              },
              {
                "description": "",
                "name": "VIXClose",
                "type": "number"
              }
            ],
            "primaryKey": "Date"
          },
          "url": "https://s3.amazonaws.com/rawstore.datahub.io/e340e16a7d5892ff193d15291eb46c95"
        },
        {
          "bytes": 30472,
          "datahub": {
            "derivedFrom": [
              "vix-daily"
            ],
            "type": "derived/json"
          },
          "encoding": "utf-8",
          "format": "json",
          "hash": "2ced06a50a4b604ca9bdf2963ee7d2f4",
          "mediatype": "text/csv",
          "name": "vix-daily_json",
          "path": "data/json/data/vix-daily.json",
          "rowcount": 322,
          "schema": {
            "fields": [
              {
                "description": "",
                "format": "fmt:%Y-%m-%d",
                "name": "Date",
                "type": "date"
              },
              {
                "description": "",
                "name": "VIXOpen",
                "type": "number"
              },
              {
                "description": "",
                "name": "VIXHigh",
                "type": "number"
              },
              {
                "description": "",
                "name": "VIXLow",
                "type": "number"
              },
              {
                "description": "",
                "name": "VIXClose",
                "type": "number"
              }
            ],
            "primaryKey": "Date"
          }
        }
      ]
    }
  ],
  "sources": [
    {
      "name": "CBOE VIX Page",
      "title": "CBOE VIX Page",
      "web": "http://www.cboe.com/micro/vix/historical.aspx"
    }
  ],
  "title": "Simple Graph Spec Tutorial",
  "views": [
    {
      "name": "simple-view-line",
      "resources": [
        "vix-daily"
      ],
      "spec": {
        "group": "Date",
        "series": [
          "VIXHigh",
          "VIXLow"
        ],
        "type": "line"
      },
      "specType": "simple",
      "title": "tutorial-on-simple-views-line"
    },
    {
      "name": "simple-view-bar",
      "resources": [
        "vix-daily"
      ],
      "spec": {
        "group": "Date",
        "series": [
          "VIXOpen",
          "VIXOpen",
          "VIXHigh",
          "VIXLow"
        ],
        "type": "bar"
      },
      "specType": "simple",
      "title": "tutorial-on-simple-views-bar"
    }
  ]
}


inside spec attribute, there are only 3 properties enough to define graph specifications:

Attribute Type Description
type String line, bar, pie (defaults to line)
group String Field name, that will be used as abscissa (usually date field)
series Array Field name(s) that will be used as ordinate

You can define multiple views for your Data Package. For example, to display line graph as presented above, we defined graph type to be a line

  ...
  "spec": {
    "type": "line",
    ...
  }

Similarly to display bar chart we've used bar type.

  ...
  "spec": {
    "type": "bar",
    ...
  }

We use Date field to display data over time, by setting group attribute to the field name

  ...
  "spec": {
    ...
    "group": "Date",
    ...
  }

You can set any number of fields to display in series attribute as an array

  ...
  "spec": {
    ...
    "series": [
      "VIXHigh",
      "VIXLow"
    ]
 }

In our case we've displayed line graph for VIXHigh and VIXLow and similarly, in the bar chart, we use all four series and all of them are presented in chart.

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 (lines 51 and 62)
title String Title for the graph (lines 52 and 63)
resources Array Data sources for this spec. It can be either resource name or index. By default it is the first resource (lines 53 and 64)
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/examples/simple-graph-spec/latest")

#Package info
print(datapackage)

#Open actual data in RStudio Viewer
View(datapackage$data$"vix-daily")

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/examples/simple-graph-spec/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/examples/simple-graph-spec/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 Data Package in JavaScript, please, follow instructions below:

Install datapackage using npm:

$ npm install [email protected]

Once the package is installed, use code snippet below


const Datapackage = require('datapackage').Datapackage

async function fetchDataPackageAndData(dataPackageIdentifier) {
  const dp = await new Datapackage(dataPackageIdentifier)
  await Promise.all(dp.resources.map(async (resource) => {
    if (resource.descriptor.format === 'geojson') {
      const baseUrl = resource._basePath.replace('/datapackage.json', '')
      const resourceUrl = `${baseUrl}/${resource._descriptor.path}`
      const response = await fetch(resourceUrl)
      resource.descriptor._values = await response.json()
    } else {
      // we assume resource is tabular for now ...
      const table = await resource.table
      // rows are simple arrays -- we can convert to objects elsewhere as needed
      const rowsAsObjects = false
      resource.descriptor._values = await table.read(rowsAsObjects)
    }
  }))

  // see the data package object
  console.dir(dp)

  // data itself is stored in Resource object, e.g. to access first resource:
  console.log(dp.resources[0]._values)

  return dp
}


fetchDataPackageAndData('https://pkgstore.datahub.io/examples/simple-graph-spec/latest/datapackage.json');

Our JavaScript is written using ES6 features. We are using node.js v7.4.0 and passing --harmony option to enable ES6:

$ node --harmony index.js

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/examples/simple-graph-spec/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')