0.1.0 • Published 5 years ago

chartjs-plugin-datasource v0.1.0

Weekly downloads
6
License
MIT
Repository
github
Last release
5 years ago

chartjs-plugin-datasource

npm Bower Travis Code Climate

Chart.js plugin for automatic data loading

Version 0.1 requires Chart.js 2.6.0 or later. If you use the sheet data source type, SheetJS 0.8.0 or later is also required.

Installation

You can download the latest version of chartjs-plugin-datasource from the GitHub releases.

To install via npm:

npm install chartjs-plugin-datasource --save

To install via bower:

bower install chartjs-plugin-datasource --save

To use CDN:

<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datasource"></script>

Usage

chartjs-plugin-datasource can be used with ES6 modules, plain JavaScript and module loaders.

chartjs-plugin-datasource requires Chart.js. If you use the sheet data source type, SheetJS (xlsx) is also required.

First, include Chart.js, xlsx.full.js (optional) and chartjs-plugin-datasource.js to your page. Note that chartjs-plugin-datasource must be loaded after the Chart.js and SheetJS libraries. Once imported, the plugin is available under the global property ChartDataSource.

Then, you need to register the plugin to enable it for all charts in the page.

Chart.plugins.register(ChartDataSource);

Or, you can enable the plugin only for specific charts.

var chart = new Chart(ctx, {
    plugins: [ChartDataSource],
    options: {
        // ...
    }
});

Now, a data source URL can be specified as shown in the example below. By default, each row in a CSV file will be mapped to one dataset, and the first column and the first row will be treated as dataset labels and index labels respectively.

options: {
    plugins: {
        datasource: {
            url: 'sample-dataset.csv'
        }
    }
}

sample-dataset.csv

,January,February,March,April,May,June,July
Temperature,7,7,10,15,20,23,26
Precipitation,8.1,14.9,41.0,31.4,42.6,57.5,36.0

Version 0.1 supports CSV, TSV (Tab-Separated Values), PSV (Pipe-Separated Values), JSON, Excel, OpenDocument and more. More data source types are to be added in the upcoming releases.

Usage in ES6 as module

Import the module as ChartDataSource, and register it in the same way as described above.

import ChartDataSource from 'chartjs-plugin-datasource';

Tutorial and Samples

You can find a tutorial and samples at nagix.github.io/chartjs-plugin-datasource.

Configuration

The plugin options can be changed at 2 different levels and with the following priority:

  • per chart: options.plugins.datasource.*
  • globally: Chart.defaults.global.plugins.datasource.*

Common options between data source types are listed below.

NameTypeDefaultDescription
typestringData source type. 'csv', 'json', 'jsonl' and 'sheet' are supported by default. If not set, the type will be determined based on the file extension in the specified URL. If the URL doesn't have an extension, 'json' will be set.
urlstringData source URL. It must have the same origin as your page, or a response must have a proper CORS header set.

CSV Data Source

The CSV data source supports delimiter-separated values such as CSV, TSV and PSV. The following options are available in 'csv' data type.

NameTypeDefaultDescription
delimiterstringDelimiter for values. If not set, the delimiter will be determined based on the file extension in the specified URL. If the URL doesn't have an extension, ',' will be set.
rowMappingstring'dataset'Element type to which each row is mapped. more...
datasetLabelsbooleantrueIf true, the first column (when rowMapping is 'dataset') or the first row (when rowMapping is 'index') will be treated as dataset labels. This option is valid when rowMapping is 'dataset' or 'index'.
indexLabelsbooleantrueIf true, the first row (when rowMapping is 'dataset') or the first column (when rowMapping is 'index') will be treated as index labels. This option is valid when rowMapping is 'dataset' or 'index'.
datapointLabelsbooleantrueIf true, the first row will be treated as property labels for Point objects. If false, ['_dataset', 'x', 'y', 'r'] will be used. This option is valid only when rowMapping is 'datapoint'.
datapointLabelMappingobject{_dataset: '_dataset', _index: 'x'}Key-value pairs for datapoint label mapping. This option is valid only when rowMapping is 'datapoint'. more...

JSON Data Source

The JSON data source supports JSON data. The following options are available in 'json' data type.

NameTypeDefaultDescription
rowMappingstring'dataset'Element type to which each row is mapped. more...
datasetLabelsstringSimplified JSONPath expression for an array of the dataset labels. This option is valid when rowMapping is 'dataset' or 'index'. If not specified but each pair of a dataset label and data is represented as a key-value pair in the objects selected by data, those keys will be used. more...
indexLabelsstringSimplified JSONPath expression for an array of the index labels. This option is valid when rowMapping is 'dataset' or 'index'. If not specified but each pair of an index label and data is represented as a key-value pair in the objects selected by data, those keys will be used. more...
datapointLabelMappingobject{_dataset: '_dataset', _index: 'x'}Key-value pairs for datapoint label mapping. This option is valid only when rowMapping is 'datapoint'. more...
datastringSimplified JSONPath expression for a two-dimensional array of the data. more...

JSON Lines Data Source

The JSON Lines data source supports JSON Lines data. The same options are supported in 'jsonl' data type as the JSON data source, but they have different default values.

NameTypeDefaultDescription
rowMappingstring'index'Element type to which each row is mapped. more...
datasetLabelsstringSimplified JSONPath expression for an array of the dataset labels. This option is valid when rowMapping is 'dataset' or 'index'. If not specified but each pair of a dataset label and data is represented as a key-value pair in the objects selected by data, those keys will be used. more...
indexLabelsstringSimplified JSONPath expression for an array of the index labels. This option is valid when rowMapping is 'dataset' or 'index'. If not specified but each pair of an index label and data is represented as a key-value pair in the objects selected by data, those keys will be used. more...
datapointLabelMappingobject{_dataset: '_dataset', _index: 'x'}Key-value pairs for datapoint label mapping. This option is valid only when rowMapping is 'datapoint'. more...
datastringSimplified JSONPath expression for a two-dimensional array of the data. more...

Simplified JSONPath

This plugin uses a simplified version of JSONPath expression to select an array or two-dimensional array from a JSON document. The top level element in JSON data is an object while that in JSON Lines data is an array. The following elements can be used in an expression.

ElementDescription
. or []Child/array operator.
*Wildcard. All objects/elements regardless their names.
[,]Union operator results in a combination of children/array indices sets.

Below are a sample JSON document, Simplified JSONPath expressions and their results.

{
    "labels": ["January", "February", "March", "April", "May"],
    "datasets": [{
        "label": "Temperature",
        "data": [7, 7, 10, 15, 20]
    }, {
        "label": "Precipitation",
        "data": [8.1, 14.9, 41.0, 31.4, 42.6]
    }]
}
Simplified JSONPath ExpressionResult
'labels'['January', 'February', 'March', 'April', 'May']
'datasets[*].label'['Temperature', 'Precipitation']
'datasets[*].data'[[7, 7, 10, 15, 20], [8.1, 14.9, 41.0, 31.4, 42.6]]
'[label[0], datasets[*].data[0]]'['January', [5, 6]]

So, the JSONPath expressions in the plugin options will look like below.

options: {
    plugins: {
        datasource: {
            url: 'sample-dataset.json',
            datasetLabels: 'datasets[*].label',
            indexLabels: 'labels',
            data: 'datasets[*].data'
        }
    }
}

A JSON document may consist of nested objects where key-value pairs represent labels and corresponding data. In that case, dataset labels and/or index labels will be retrieved automatically, and there is no need to specify datasetLabels and indexLabels options. The following example will generate the same chart as the previous one.

{
    "Temperature": {
        "January": 7,
        "February": 7,
        "March": 10,
        "April": 15,
        "May": 20
    },
    "Precipitation": {
        "January": 8.1,
        "February": 14.9,
        "March": 41.0,
        "April": 31.4,
        "May": 42.0
    }
}
options: {
    plugins: {
        datasource: {
            url: 'sample-dataset.json',
            data: '*.*'
        }
    }
}

If you want to specify the order of labels explicitly, you can use union operators as shown below.

options: {
    plugins: {
        datasource: {
            url: 'sample-dataset.json',
            data: '[Temperature, Precipitation][January, February, March, April, May]'
        }
    }
}

Sheet Data Source

The sheet data source supports various spreadsheet formats such as Excel and OpenDocument. The following options are available in 'sheet' data type.

NameTypeDefaultDescription
rowMappingstring'dataset'Element type to which each row is mapped. more...
datasetLabelsstringRange for dataset labels (A1 Notation). This option is valid when rowMapping is 'dataset' or 'index'. If neither datasetLabels nor data are specified, the first column or row from the auto-detected range will be selected.
indexLabelsstringRange for index labels (A1 Notation). This option is valid when rowMapping is 'dataset' or 'index'. If neither indexLabels nor data are specified, the first row or column from the auto-detected range will be selected.
datapointLabelsstringRange for property labels for Point objects (A1 Notation). This option is valid only when rowMapping is 'datapoint'. If neither datapointLabels nor data are specified, the first row from the auto-detected range will be selected. If no data is found, ['_dataset', 'x', 'y', 'r'] will be used.
datapointLabelMappingobject{_dataset: '_dataset', _index: 'x'}Key-value pairs for datapoint label mapping. This option is valid only when rowMapping is 'datapoint'. more...
datastringRange for the data (A1 Notation). If not specified, the range will be detected automatically.

A1 Notation

Some options require a range in A1 notation. This is a string like Sheet1!A1:B2 that refers to a group of cells in the spreadsheet. For example, valid ranges are:

  • Sheet1!A1:B2 refers to the first two cells in the top two rows of Sheet1.
  • Sheet1!A:A refers to all the cells in the first column of Sheet1.
  • Sheet1!1:2 refers to the all the cells in the first two rows of Sheet1.
  • Sheet1!A5:A refers to all the cells of the first column of Sheet 1, from row 5 onward.
  • A1:B2 refers to the first two cells in the top two rows of the first visible sheet.
  • Sheet1 refers to all the cells in Sheet1.

If the sheet name has spaces or starts with a bracket, surround the sheet name with single quotes ('), e.g 'Sheet One'!A1:B2. For simplicity, it is safe to always surround the sheet name with single quotes.

Row Mapping

rowMapping indicates an element type to which each row is mapped. Available values are listed below.

  • 'dataset'
  • 'index'
  • 'datapoint'

When each row contains values for one dataset, 'dataset' is used. In many cases, the first column contains dataset labels and the first row contains index labels. Below is an example of dataset-mapped rows.

JanuaryFebruaryMarchAprilMay
Temperature77101520
Precipitation8.114.941.031.442.6

When each row contains values for one index, 'index' is used. In many cases, the first column contains index labels and the first row contains dataset labels. Below is an example of index-mapped rows.

TemperaturePrecipitation
January78.1
February714.9
March1041.0
April1531.4
May2042.6

When each row contains values for one data point, 'datapoint' is used. This type of data formatting is often called Tidy Data. The first row can have datapoint labels. Below is an example of datapoint-mapped rows.

datasetmonthvalue
TemperatureJanuary7
TemperatureFebruary7
TemperatureMarch10
TemperatureApril15
TemperatureMay20
PrecipitationJanuary8.1
PrecipitationFebruary14.9
PrecipitationMarch41.0
PrecipitationApril31.4
PrecipitationMay42.6

Datapoint Label Mapping

If rowMapping is 'datapoint', datapointLabelMapping can be used to correspond each column to specific datapoint property. It consists of key-value pairs where the key is a property name in Point data used in the line chart, bubble chart and scatter chart, and the value is a datapoint label specified by the datapointLabels option or a property name in case of 'json' and 'jsonl' data sources.

The following keys are used to indicate a special usage of the column.

  • _dataset: This column is treated as dataset labels
  • _index: This column is treated as index labels

In the following example, the values in the column labeled as 'month' will be mapped to the property x, and the ones in the column labeled as 'value' will be mapped to the property y.

datapointLabelMapping: {
    _dataset: 'dataset',
    _index: 'month',
    x: 'month',
    y: 'value'
}

If the data source type is 'csv', a value can be a number instead of a label text. In that case, it indicates the column index starting with 0. If the data source type is 'sheet', a value can be a column-only A1 notation (for example, 'B' indicates the second column). Below is an example of a CSV data source specifying the column index for each property in Point data.

datapointLabelMapping: {
    _dataset: 0,
    _index: 1,
    x: 1,
    y: 2
}

Supported Data Format

All supported data formats are listed below.

DataSourceTypeFormatExtensionDescription
CSVCSVcsvRFC 4180-compliant Comma-Separated Values. The default delimiter is ','.
CSVTSVtsvTab-Separated Values. The default delimiter is '\t'.
CSVPSVpsvPipe-Separated Values. The default delimiter is '|'.
JSONJSONjsonJSON
JSON LinesJSON LinesjsonlJSON Lines
SheetXLSX/XLSMxlsx xlsmExcel 2007+ XML Formats
SheetXLSB BIFF12xlsbExcel 2007+ Binary
SheetXML SpreadsheetMLxmlExcel 2003-2004 XML Format
SheetXLS BIFF8xlsExcel 97-2004
SheetXLS BIFF5xlsExcel 5.0/95
SheetXLS/XLW BIFF4xls xlwExcel 4.0
SheetXLS BIFF3xlsExcel 3.0
SheetXLS BIFF2xlsExcel 2.0/2.1
SheetCSV/TXTcsv txtDelimiter-Separated Values
SheetDIFdifData Interchange Format
SheetSYLK/SLKsylk slkSymbolic Link
SheetPRNprnLotus Formatted Text
SheetTXTtxtUTF-16 Unicode Text
SheetODSodsOpenDocument Spreadsheet
SheetDODSfodsFlat XML ODF Spreadsheet
Sheet标文通 UOS1/UOS2uosUniform Office Format Spreadsheet
SheetDBFdbfdBASE II/III/IV / Visual FoxPro
SheetWKS/WK1/WK2/WK3/WK4/123wks wk1 wk2 wk3 wk4 123Lotus 1-2-3
SheetWQ1/WQ2/WB1/WB2/WB3/QPWwq1 wq2 wb1 wb2 wb3 qpwQuattro Pro Spreadsheet
SheetHTMLhtml htmHTML Tables
SheetETHethEtherCalc Record Format

Cross-Origin Resource Sharing (CORS)

If your data source doesn't share the origin (domain, protocol and port) with your page, the HTTP response from the data source must include the right CORS headers to allow cross-site requests. Modern browsers handle the client-side components of cross-origin sharing, including headers and policy enforcement, and no extra code or configuration is required in your page. But, the server at the data source needs to have the proper configuration to handle requests and response headers.

Response HTTP headers must include at least the following header, which indicates that requests from this origin will be allowed.

Access-Control-Allow-Origin: [<scheme>:]<domain>[:<port>]

The value can also be * which means that the resource can be accessed by any domain in a cross-site manner.

Access-Control-Allow-Origin: *

See Cross-Origin Resource Sharing (CORS) for more details.

Building

You first need to install node dependencies (requires Node.js):

npm install

The following commands will then be available from the repository root:

gulp build            # build dist files
gulp build --watch    # build and watch for changes
gulp lint             # perform code linting
gulp package          # create an archive with dist files and samples

License

chartjs-plugin-datasource is available under the MIT license.