### PivotTable.js with Function Input
Source: https://github.com/nicolaskruchten/pivottable/blob/master/examples/simple_function.html
This example uses a JavaScript function to provide input values to the pivot() method. Ensure the DOM is ready before initializing the pivot table.
```javascript
body {
font-family: Verdana;
}
// This example uses a function to provide the input values to pivot()
$(function () {
var lookupColour = ["blue", "yellow"];
var rawData = [
{ color: 0, shape: "circle"},
{ color: 1, shape: "circle"},
{ color: 1, shape: "circle"},
{ color: 0, shape: "triangle"},
{ color: 0, shape: "triangle"},
{ color: 1, shape: "triangle"}
];
var inputFunction = function (callback) {
rawData.forEach(function (element, index) {
callback({ color: lookupColour[element.color], shape: element.shape });
});
};
$("#output").pivot(inputFunction, { rows: ["color"], cols: ["shape"] });
});
```
--------------------------------
### Interactive Pivot Table with pivotUI()
Source: https://context7.com/nicolaskruchten/pivottable/llms.txt
Creates a full-featured interactive pivot table using `pivotUI()`. This example loads data from 'data.json' and configures rows, columns, aggregators, renderers, and UI options.
```javascript
$.getJSON("data.json", function(data) {
$"#output".pivotUI(data, {
rows: ["Province"],
cols: ["Party"],
vals: ["Age"],
aggregatorName: "Integer Sum",
rendererName: "Heatmap",
hiddenAttributes: ["ID", "InternalCode"],
hiddenFromAggregators: ["Name", "Date"],
hiddenFromDragDrop: ["RecordID"],
exclusions: {
Province: ["Unknown", "N/A"]
},
menuLimit: 500,
autoSortUnusedAttrs: true,
unusedAttrsVertical: true,
showUI: true,
rendererOptions: {
table: {
rowTotals: true,
colTotals: true,
clickCallback: function(e, value, filters, pivotData) {
var names = [];
pivotData.forEachMatchingRecord(filters, function(record) {
names.push(record.Name);
});
alert("Records: " + names.join(", "));
}
}
},
onRefresh: function(config) {
console.log("Pivot configuration updated:", config);
}
});
});
```
--------------------------------
### PivotTable.js Custom Aggregators
Source: https://context7.com/nicolaskruchten/pivottable/llms.txt
Illustrates creating custom aggregators using templates and defining aggregator functions directly. Includes examples for custom formatting and registering new aggregators.
```javascript
// Custom aggregator using templates
var tpl = $.pivotUtilities.aggregatorTemplates;
var fmt = $.pivotUtilities.numberFormat;
// Custom currency formatter
var currencyFormat = fmt({
prefix: "$",
thousandsSep: ",",
decimalSep: ".",
digitsAfterDecimal: 2
});
// Success rate aggregator
var successRateAgg = tpl.sumOverSum(fmt({
digitsAfterDecimal: 1,
scaler: 100,
suffix: "%"
}))(["Wins", "TotalGames"]);
```
```javascript
// Fully custom aggregator function
var weightedAverage = function(attributeArray) {
var valueAttr = attributeArray[0];
var weightAttr = attributeArray[1];
return function(data, rowKey, colKey) {
return {
sumProduct: 0,
sumWeights: 0,
push: function(record) {
var val = parseFloat(record[valueAttr]);
var weight = parseFloat(record[weightAttr]);
if (!isNaN(val) && !isNaN(weight)) {
this.sumProduct += val * weight;
this.sumWeights += weight;
}
},
value: function() {
return this.sumWeights > 0 ? this.sumProduct / this.sumWeights : 0;
},
format: currencyFormat,
numInputs: 2
};
};
};
// Register custom aggregator for pivotUI
var customAggregators = $.extend({}, $.pivotUtilities.aggregators, {
"Weighted Average": weightedAverage
});
$("#output").pivotUI(data, {
aggregators: customAggregators,
aggregatorName: "Weighted Average",
vals: ["Price", "Quantity"]
});
```
--------------------------------
### Writing Custom Aggregators
Source: https://github.com/nicolaskruchten/pivottable/wiki/Aggregators
Guide on creating custom aggregation functions for specific data attributes and desired calculations, useful for reporting systems.
```APIDOC
## Writing your own aggregators
If you are using PivotTable.js in a context where you already know the attribute-names in the data, as well as the types of cell-values your users will want to see (i.e. you are writing a reporting system) then you can create your own aggregation functions so that users will not have to drag attributes into the aggregator-function box in the UI.
As an example, let's say you are using PivotTable.js to generate summary tables for data which has a `trials` attribute and a `successes` attribute and you know that your users will care a lot about the success rate, which is defined as the sum of successes over the sum of trials. You could therefore create an aggregator-generating function to pass into `pivotUI()` in the `aggregators` dictionary defined as follows:
```javascript
var successRate = function() {
return function() {
return {
sumSuccesses: 0,
sumTrials: 0,
push: function(record) {
if (!isNaN(parseFloat(record.successes))) {
this.sumSuccesses += parseFloat(record.successes);
}
if (!isNaN(parseFloat(record[denom]))) {
return this.sumTrials += parseFloat(record.trials);
}
},
value: function() { return this.sumSuccesses / this.sumTrials; },
format: function(x) { return x; },
numInputs: 0
};
};
};
```
```
--------------------------------
### Create Sum Over Sum with French Formatting
Source: https://github.com/nicolaskruchten/pivottable/wiki/Aggregators
Utilize the numberFormat helper to create custom locale-specific formatters. This example applies French number formatting to a sumOverSum aggregator.
```javascript
var sumOverSum = $.pivotUtilities.aggregatorTemplates.sumOverSum;
var numberFormat = $.pivotUtilities.numberFormat;
var frFormat = numberFormat({thousandsSep:" ", decimalSep:","});
var successRate = function() { return sumOverSum(frFormat)(["successes", "trials"]); }
```
--------------------------------
### C3 Scatterplot Renderer with CSV Input
Source: https://github.com/nicolaskruchten/pivottable/blob/master/examples/scatter.html
This example demonstrates the C3 Scatterplot renderer using data fetched and parsed from a CSV file. Ensure PapaParse is included for CSV parsing.
```javascript
$(function(){
Papa.parse("https://raw.githubusercontent.com/nicolaskruchten/Rdatasets/master/csv/datasets/iris.csv", {
download: true,
skipEmptyLines: true,
complete: function(parsed){
$("#output").pivot(parsed.data, {
rows: ["Petal.Length"],
cols: ["Petal.Width", "Species"],
renderer: $.pivotUtilities.c3_renderers["Scatter Chart"],
rendererOptions: {
c3: {
size: {width: 600, height: 600}
}
}
});
}
});
});
```
--------------------------------
### Basic Table Renderer
Source: https://context7.com/nicolaskruchten/pivottable/llms.txt
Use the basic table renderer for a standard tabular display of pivot data. No special setup is required beyond initializing the pivot table.
```javascript
// Basic table renderer
$("#output").pivot(data, {
rows: ["Category"],
cols: ["Month"],
renderer: $.pivotUtilities.renderers["Table"]
});
```
--------------------------------
### Load Data and Add Derived Attributes with Pivot Table.js
Source: https://github.com/nicolaskruchten/pivottable/blob/master/examples/mps.html
This example loads the 'Canadian Parliament 2012' dataset from a JSON file and adds derived attributes for 'Age Bin' and 'Gender Imbalance' to the pivot table.
```javascript
body {
font-family: Verdana;
}
// This example loads the "Canadian Parliament 2012" dataset
// and adds derived attributes: "Age Bin" and "Gender Imbalance".
$(function(){
var derivers = $.pivotUtilities.derivers;
$.getJSON("mps.json", function(mps) {
$("#output").pivotUI(mps, {
derivedAttributes: {
"Age Bin": derivers.bin("Age", 10),
"Gender Imbalance": function(mp) {
return mp["Gender"] == "Male" ? 1 : -1;
}
}
});
});
});
```
--------------------------------
### Custom Aggregators and Sorters with PivotTable.js
Source: https://github.com/nicolaskruchten/pivottable/blob/master/examples/mps_agg.html
This example configures PivotTable.js to use custom aggregators for counting MPs and calculating average age, and custom sorters for 'Province' and 'Age'. It requires the 'mps.json' dataset.
```javascript
body {
font-family: Verdana;
}
// This example shows custom aggregators and sorters using
// the "Canadian Parliament 2012" dataset.
$(function(){
var tpl = $.pivotUtilities.aggregatorTemplates;
$.getJSON("mps.json", function(mps) {
$("#output").pivotUI(mps, {
rows: ["Province"],
cols: ["Party"],
aggregators: {
"Number of MPs": function() { return tpl.count()() },
"Average Age of MPs": function() { return tpl.average()(["Age"])}
},
sorters: {
Province: $.pivotUtilities.sortAs(
["British Columbia", "Alberta", "Saskatchewan", "Manitoba", "Territories", "Ontario", "Quebec", "New Brunswick", "Prince Edward Island", "Nova Scotia", "Newfoundland and Labrador"]
),
Age: function(a,b){ return b-a; } //sort backwards
}
});
});
});
```
--------------------------------
### Basic Pivot Table Rendering with pivot()
Source: https://context7.com/nicolaskruchten/pivottable/llms.txt
Demonstrates basic usage of the `pivot()` function with an array of objects to create a static pivot table. Specify rows, columns, and the aggregator.
```javascript
$"#output".pivot(
[
{color: "blue", shape: "circle", size: 10},
{color: "red", shape: "triangle", size: 15},
{color: "blue", shape: "square", size: 20},
{color: "red", shape: "circle", size: 25}
],
{
rows: ["color"],
cols: ["shape"],
aggregator: $.pivotUtilities.aggregators["Sum"](["size"]),
aggregatorName: "Sum",
rowOrder: "key_a_to_z",
colOrder: "key_a_to_z"
}
);
```
--------------------------------
### Get Aggregator for Specific Cell
Source: https://context7.com/nicolaskruchten/pivottable/llms.txt
Use getAggregator with specific row and column keys to get the aggregation object for a particular cell in the pivot table.
```javascript
// Get aggregator for specific cell
var agg = pivotData.getAggregator(["East"], ["Widget"]);
console.log("Value:", agg.value());
console.log("Formatted:", agg.format(agg.value()));
```
--------------------------------
### pivotUI(input, options, overwrite, locale)
Source: https://github.com/nicolaskruchten/pivottable/wiki/Parameters
Initializes the PivotTable UI and handles data rendering based on user interactions.
```APIDOC
## pivotUI(input [,options [,overwrite [,locale]]])
### Description
pivotUI() draws a UI and calls pivot() whenever the UI is changed via drag'n'drop or aggregator selection. It allows for configuration of visualizations, aggregators, and initial state.
### Parameters
- **input** (array/function/jQuery object) - Required - The data source, which can be an array of objects, array of arrays, a function, or a jQuery object referencing a table.
- **options** (object) - Optional - Configuration object for UI elements, aggregators, and effects.
- **overwrite** (boolean) - Optional - Defaults to false. If true, the options object overwrites the current state of the UI on repeated calls.
- **locale** (string) - Optional - Defaults to 'en'. Controls the default locale for number formatting and error messages.
```
--------------------------------
### Define a 'count' aggregator function
Source: https://github.com/nicolaskruchten/pivottable/wiki/Aggregators
This function counts the number of records that match a cell. It is a basic example of an aggregator function for the `pivot()` function.
```javascript
var count = function(data, rowKey, colKey) {
return {
count: 0,
push: function(record) { this.count++; },
value: function() { return this.count; },
format: function(x) { return x; },
};
};
```
--------------------------------
### Initialize PivotTable.js with Renderers
Source: https://github.com/nicolaskruchten/pivottable/blob/master/examples/local.html
This code initializes the PivotTable.js plugin, extending it with various renderers for data visualization and export. It's typically run on document ready.
```javascript
var renderers = $.extend( $.pivotUtilities.renderers, $.pivotUtilities.c3_renderers, $.pivotUtilities.d3_renderers, $.pivotUtilities.export_renderers );
```
--------------------------------
### Get Totals from PivotData
Source: https://context7.com/nicolaskruchten/pivottable/llms.txt
Retrieve row totals, column totals, and the grand total by calling getAggregator with empty arrays for row or column keys.
```javascript
// Get totals
var rowTotal = pivotData.getAggregator(["East"], []); // Row total
var colTotal = pivotData.getAggregator([], ["Widget"]); // Column total
var grandTotal = pivotData.getAggregator([], []); // Grand total
```
--------------------------------
### Basic Pivot Table Initialization
Source: https://github.com/nicolaskruchten/pivottable/blob/master/examples/simple.html
Initializes a pivot table with sample data, specifying 'color' for rows and 'shape' for columns. Requires jQuery and PivotTable.js to be loaded.
```javascript
body {
font-family: Verdana;
}
$(function(){
$("#output").pivot(
[
{color: "blue", shape: "circle"},
{color: "red", shape: "triangle"}
],
{
rows: ["color"],
cols: ["shape"]
}
);
});
```
--------------------------------
### PivotTable.js Input Data Formats
Source: https://context7.com/nicolaskruchten/pivottable/llms.txt
Demonstrates how to initialize PivotTable.js with different data structures: arrays of objects, arrays of arrays, functions for lazy loading, direct jQuery table references, and CSV parsing with PapaParse.
```javascript
// Array of objects (most common)
var dataObjects = [
{name: "Alice", department: "Sales", salary: 50000},
{name: "Bob", department: "Engineering", salary: 75000},
{name: "Carol", department: "Sales", salary: 55000}
];
$("#output").pivotUI(dataObjects);
```
```javascript
// Array of arrays (first row is headers)
var dataArrays = [
["name", "department", "salary"],
["Alice", "Sales", 50000],
["Bob", "Engineering", 75000],
["Carol", "Sales", 55000]
];
$("#output").pivotUI(dataArrays);
```
```javascript
// Function callback (for streaming/lazy loading)
var dataFunction = function(callback) {
callback({name: "Alice", department: "Sales", salary: 50000});
callback({name: "Bob", department: "Engineering", salary: 75000});
// Can make AJAX calls or process large files incrementally
};
$("#output").pivotUI(dataFunction);
```
```javascript
// jQuery reference to HTML table
$("#output").pivotUI($("#sourceTable"));
```
```javascript
// CSV parsing with PapaParse
Papa.parse("employees.csv", {
download: true,
complete: function(results) {
$("#output").pivotUI(results.data);
}
});
```
--------------------------------
### Initialize a basic pivot table
Source: https://github.com/nicolaskruchten/pivottable/blob/master/README.md
Use the pivot() function to render a static pivot table from a dataset.
```javascript
$("#output").pivot(
[
{color: "blue", shape: "circle"},
{color: "red", shape: "triangle"}
],
{
rows: ["color"],
cols: ["shape"]
}
);
```
--------------------------------
### Initialize PivotTable.js with French Localization
Source: https://github.com/nicolaskruchten/pivottable/blob/master/examples/mps_fr.html
This snippet initializes PivotTable.js, fetching data from 'mps.json' and configuring it for French localization with specified rows and columns. Ensure the 'mps.json' file is accessible.
```javascript
$(function(){
$.getJSON("mps.json", function(mps) {
$("#output").pivotUI(mps, {
rows: ["Province"],
cols: ["Party"]
}, false, "fr" );
});
});
```
--------------------------------
### Initialize PivotTable.js UI with JSON data
Source: https://github.com/nicolaskruchten/pivottable/blob/master/examples/mps_prepop.html
Uses jQuery to fetch a JSON file and initialize the pivotUI component with specific rows, columns, and renderer settings.
```javascript
$(function(){ $.getJSON("mps.json", function(mps) { $("#output").pivotUI(mps, { rows: ["Province"], cols: ["Party"], aggregatorName: "Integer Sum", vals: ["Age"], rendererName: "Heatmap", rendererOptions: { table: { clickCallback: function(e, value, filters, pivotData){ var names = []; pivotData.forEachMatchingRecord(filters, function(record){ names.push(record.Name); }); alert(names.join("\n")); } } } }); }); });
```
--------------------------------
### Initialize PivotTable.js with C3 Renderers
Source: https://github.com/nicolaskruchten/pivottable/blob/master/examples/c3.html
This code initializes PivotTable.js with C3 renderers, configuring chart colors and layout for the pivot table. It fetches data from 'mps.json' and renders a 'Horizontal Stacked Bar Chart'.
```javascript
body {
font-family: Verdana;
}
.c3-line,
.c3-focused {
stroke-width: 3px !important;
}
.c3-bar {
stroke: white !important;
stroke-width: 1;
}
.c3 text {
font-size: 12px;
color: grey;
}
.tick line {
stroke: white;
}
.c3-axis path {
stroke: grey;
}
.c3-circle {
opacity: 1 !important;
}
.c3-xgrid-focus {
visibility: hidden !important;
}
// This example adds C3 chart renderers.
$(function() {
var derivers = $.pivotUtilities.derivers;
var renderers = $.extend(
$.pivotUtilities.renderers,
$.pivotUtilities.c3_renderers
);
$.getJSON("mps.json", function(mps) {
$("#output").pivotUI(mps, {
renderers: renderers,
cols: ["Party"],
rows: ["Province"],
rendererName: "Horizontal Stacked Bar Chart",
rowOrder: "value_z_to_a",
colOrder: "value_z_to_a",
rendererOptions: {
c3: {
data: {
colors: {
Liberal: '#dc3912',
Conservative: '#3366cc',
NDP: '#ff9900',
Green: '#109618',
'Bloc Quebecois': '#990099'
}
}
}
}
});
});
});
```
--------------------------------
### PivotUI Options Object
Source: https://github.com/nicolaskruchten/pivottable/wiki/Parameters
Configuration options for the pivotUI() function.
```APIDOC
## PivotUI Options Object
This section details the configuration options available for the `pivotUI()` function, which allows for extensive customization of the pivot table interface.
### Options Table
| Key | Type | Default value | Description |
|---|---|---|---|
| `rows` | array of strings | `[]` | Attribute names to prepopulate in the row area. |
| `cols` | array of strings | `[]` | Attribute names to prepopulate in the column area. |
| `vals` | array of strings | `[]` | Attribute names to prepopulate in the values area (passed to the aggregator generating function). |
| `aggregators` | object of functions | `$.pivotUtilities.aggregators` | Dictionary of generators for aggregation functions available in the dropdown. Refer to the [Aggregators documentation](https://github.com/nicolaskruchten/pivottable/wiki/Aggregators) for more details. |
| `aggregatorName` | string | First key in `aggregators` | The name of the aggregator to prepopulate in the dropdown (key to the `aggregators` object). |
| `renderers` | object of functions | `$.pivotUtilities.renderers` | Dictionary of rendering functions. Refer to the [Renderers documentation](https://github.com/nicolaskruchten/pivottable/wiki/Renderers) for more details. |
| `rendererName` | string | First key in `renderers` | The name of the renderer to prepopulate in the dropdown (key to the `renderers` object). |
| `rowOrder` | string | `"key_a_to_z"` | The order in which row data is provided to the renderer. Must be one of `"key_a_to_z"`, `"value_a_to_z"`, `"value_z_to_a"`. Ordering by value sorts by row total. |
| `colOrder` | string | `"key_a_to_z"` | The order in which column data is provided to the renderer. Must be one of `"key_a_to_z"`, `"value_a_to_z"`, `"value_z_to_a"`. Ordering by value sorts by column total. |
| `derivedAttributes` | object of functions | `{}` | Defines derived attributes. Refer to the [Derived Attributes documentation](https://github.com/nicolaskruchten/pivottable/wiki/Derived-Attributes) for more details. |
| `dataClass` | function | `$.pivotUtilities.PivotData` | Constructor for the data class to be built and passed to the Renderer. Should be a subclass of the default. |
| `filter` | function | `function(){return true;}` | A function called on each record. Returns `false` if the record should be excluded before rendering, `true` otherwise. |
| `inclusions` | object of arrays of strings | `{}` | An object where keys are attribute names and values are arrays of attribute values to include in rendering. Used to prepopulate filter menus that appear on double-click (overrides `exclusions`). |
| `exclusions` | object of arrays of strings | `{}` | An object where keys are attribute names and values are arrays of attribute values to exclude from rendering. Used to prepopulate filter menus that appear on double-click. |
| `hiddenAttributes` | array of strings | `[]` | Contains attribute names to omit from the UI. |
| `hiddenFromAggregators` | array of strings | `[]` | Contains attribute names to omit from the aggregator arguments dropdowns. |
| `hiddenFromDragDrop` | array of strings | `[]` | Contains attribute names to omit from the drag'n'drop portion of the UI. |
| `sorters` | object or function | `{}` | Accessed or called with an attribute name. Can return a function usable with `Array.sort` for output purposes. If no function is returned, a default natural sort is used. Useful for sorting attributes like month names. See [example 1](http://nicolas.kruchten.com/pivottable/examples/mps_agg.html) and [example 2](http://nicolas.kruchten.com/pivottable/examples/montreal_2014.html). |
| `onRefresh` | function | `function(){}` | Called upon renderer refresh with an object representing the current UI settings. See [example](http://nicolas.kruchten.com/pivottable/examples/onrefresh.html). |
| `menuLimit` | integer | `50` | Maximum number of values to list in the double-click menu. |
| `autoSortUnusedAttrs` | boolean | `false` | Controls whether unused attributes are kept sorted in the UI. |
| `unusedAttrsVertical` | boolean or integer | `85` | Controls whether unused attributes are shown vertically (default is horizontal). `true` means always vertical, `false` means always horizontal. If set to a number, attributes will be shown vertically if their combined name length exceeds that number. |
| `showUI` | boolean | `true` | Controls whether the drag'n'drop UI is shown. Set to `false` to emulate `pivot()` behavior with the `pivotUI()` signature. |
| `rendererOptions` | object | `{}` | Passed through to the renderer as options. See [[Renderers]] and [[Optional Extra Renderers]] for details. |
| `localeStrings` | object | `en` strings | Locale-specific strings for UI display. See `locale` parameter below. |
```
--------------------------------
### Initialize PivotTable.js with TSV Export
Source: https://github.com/nicolaskruchten/pivottable/blob/master/examples/mps_export.html
Initializes PivotTable.js with the 'TSV Export' renderer. Ensure the PivotTable.js library and its dependencies are included. This code fetches data from 'mps.json' and renders it into the '#output' element.
```javascript
body {
font-family: Verdana;
}
// When using the 'TSV Export' Renderer, you can
// copy from this textarea straight into Excel.
$(function(){
var renderers = $.extend($.pivotUtilities.renderers, $.pivotUtilities.export_renderers);
$.getJSON("mps.json", function(mps) {
$("#output").pivotUI(mps, {
renderers: renderers,
cols: ["Party"],
rows: ["Province"],
rendererName: "TSV Export"
});
});
});
```
--------------------------------
### Initialize PivotTable.js from HTML Table
Source: https://github.com/nicolaskruchten/pivottable/blob/master/examples/simple_ui_from_table.html
Uses jQuery to select an HTML table and transform it into a pivot interface with specified rows and columns.
```javascript
$(function(){ $("#output").pivotUI($("#input"), { rows: ["color"], cols: ["shape"] }); });
```
--------------------------------
### pivot(input, options, locale)
Source: https://github.com/nicolaskruchten/pivottable/wiki/Parameters
The pivot() function processes input data and renders an HTML summary table based on the provided configuration options.
```APIDOC
## pivot(input [,options [,locale]])
### Description
Injects an HTML table into the object onto which it is called, summarizing the input data according to the provided options.
### Parameters
#### Path Parameters
- **input** (array/function/jQuery object) - Required - The data source to be summarized.
- **options** (object) - Optional - Configuration object for the pivot table.
- **locale** (string) - Optional - Locale code for formatting and error messages (defaults to 'en').
### Options Object
- **rows** (array of strings) - Array of attribute names to use as rows.
- **cols** (array of strings) - Array of attribute names for use as columns.
- **aggregator** (function) - Constructor for an object which will aggregate results per cell.
- **aggregatorName** (string) - Name of the aggregator for display purposes.
- **renderer** (function) - Generates output from pivot data structure.
- **rowOrder** (string) - Order of row data ('key_a_to_z', 'value_a_to_z', 'value_z_to_a').
- **colOrder** (string) - Order of column data ('key_a_to_z', 'value_a_to_z', 'value_z_to_a').
- **derivedAttributes** (object) - Object to define derived attributes.
- **dataClass** (function) - Constructor for the data class.
- **filter** (function) - Called on each record; returns false to exclude the record.
- **sorters** (object/function) - Used for custom sorting of attributes.
- **rendererOptions** (object) - Options passed through to the renderer.
- **localeStrings** (object) - Locale-specific strings for error messages.
```
--------------------------------
### Load and Render Pivot Table with Serialized Config
Source: https://github.com/nicolaskruchten/pivottable/blob/master/examples/text_config.html
Use this when loading a configuration that has been serialized to text. You must merge it with an object containing the aggregators, renderers, and sorters, as functions cannot be serialized to text.
```javascript
body {
font-family: Verdana;
}
// If you are loading a configuration which has been serialized to text,
// you will need to merge it with an object containing the aggregators,
// renderers, and sorters you wish to use, because functions cannot be
// serialized to text.
$(function(){
$.getJSON("mps.json", function(mps) {
// these are the functions you wish to use
var functionsConfig = {
aggregators: $.pivotUtilities.aggregators,
renderers: $.pivotUtilities.renderers,
sorters: {
Province: $.pivotUtilities.sortAs([
"British Columbia",
"Alberta",
"Saskatchewan",
"Manitoba",
"Territories",
"Ontario",
"Quebec",
"New Brunswick",
"Prince Edward Island",
"Nova Scotia",
"Newfoundland and Labrador"
]),
Age: function(a, b) { return b - a; }
}
};
// this is your saved/serialized config in a string
var serializedConfig = '{"rows":["Province"], "cols":["Party"],'+
'"vals":["Age"],"aggregatorName":"Integer Sum"}';
// deserialized it into an object
var deserializedConfig = JSON.parse(serializedConfig)
// merge the deserialized object with the functions object
var mergedConfig = $.extend({}, functionsConfig, deserializedConfig);
$("#output").pivotUI(mps, mergedConfig);
});
});
```
--------------------------------
### Basic PivotTable.js Usage
Source: https://github.com/nicolaskruchten/pivottable/blob/master/examples/simple_ui.html
Use this for the most basic implementation of pivotUI(). Ensure the target element exists and the data is properly formatted.
```javascript
body {
font-family: Verdana;
}
// This example is the most basic usage of pivotUI()
$(function(){
$("#output").pivotUI(
[
{color: "blue", shape: "circle"},
{color: "red", shape: "triangle"}
],
{
rows: ["color"],
cols: ["shape"]
}
);
});
```
--------------------------------
### Initialize PivotTable.js with JSON data
Source: https://github.com/nicolaskruchten/pivottable/blob/master/examples/mps_rename.html
Uses jQuery to fetch a JSON file and pass the data into the pivotUI function. Ensure the target element exists in the DOM before initialization.
```javascript
$(function(){
$.getJSON("mps.json", function(mps) {
$("#output").pivotUI(function(injectRecord){
mps.map(function(mp) {
injectRecord({a: mp.Age, b: mp.Name, c: mp.Province});
});
});
});
});
```
--------------------------------
### Initialize PivotTable.js with D3 Treemap Renderer
Source: https://github.com/nicolaskruchten/pivottable/blob/master/examples/d3.html
Uses jQuery to fetch JSON data and initialize the pivot table with the D3 treemap renderer.
```javascript
$(function(){ $.getJSON("mps.json", function(mps) { $("#output").pivotUI(mps, { renderers: $.pivotUtilities.d3_renderers, cols: [], rows: ["Province", "Party"], rendererName: "Treemap" }); }); });
```
--------------------------------
### Load C3/D3 Chart Dependencies
Source: https://context7.com/nicolaskruchten/pivottable/llms.txt
Include the necessary CSS and JavaScript files for D3.js, C3.js, and the corresponding pivotTable.js renderers extensions to use C3/D3 charts.
```html
```
--------------------------------
### Pivot Table with Filtering and Derived Attributes using pivot()
Source: https://context7.com/nicolaskruchten/pivottable/llms.txt
Shows how to use `pivot()` with custom filtering and derived attributes. The `filter` function excludes records, and `derivedAttributes` computes new values like 'Profit Margin'.
```javascript
$"#output".pivot(salesData, {
rows: ["Region", "Category"],
cols: ["Quarter"],
aggregator: $.pivotUtilities.aggregators["Average"](["Revenue"]),
filter: function(record) {
return record.Revenue > 1000;
},
derivedAttributes: {
"Profit Margin": function(record) {
return ((record.Revenue - record.Cost) / record.Revenue * 100).toFixed(1) + "%";
}
},
sorters: {
Quarter: $.pivotUtilities.sortAs(["Q1", "Q2", "Q3", "Q4"])
}
});
```
--------------------------------
### Initialize PivotTable.js with Custom Renderers
Source: https://github.com/nicolaskruchten/pivottable/blob/master/examples/fully_loaded.html
Configures the pivot table with C3, D3, and export renderers, and defines custom derived attributes for data grouping and calculation.
```javascript
$(function(){
var derivers = $.pivotUtilities.derivers;
var renderers = $.extend(
$.pivotUtilities.renderers,
$.pivotUtilities.c3_renderers,
$.pivotUtilities.d3_renderers,
$.pivotUtilities.export_renderers
);
$.getJSON("mps.json", function(mps) {
$("#output").pivotUI(mps, {
renderers: renderers,
derivedAttributes: {
"Age Bin": derivers.bin("Age", 10),
"Gender Imbalance": function(mp) {
return mp["Gender"] == "Male" ? 1 : -1;
}
},
cols: ["Age Bin"],
rows: ["Gender"],
rendererName: "Table Barchart"
});
});
});
```
--------------------------------
### Load and Render Montreal Weather Data with PivotTable.js
Source: https://github.com/nicolaskruchten/pivottable/blob/master/examples/montreal_2014.html
This snippet loads the 'Montreal Weather 2014' dataset from a CSV file. It configures PivotTable.js to handle dates, define custom aggregators with formatting, set up sorting for months and days, and render the data as a heatmap using C3.js. Ensure PapaParse and D3.js are included for CSV parsing and C3 rendering.
```javascript
$(function () {
var dateFormat = $.pivotUtilities.derivers.dateFormat;
var sortAs = $.pivotUtilities.sortAs;
var tpl = $.pivotUtilities.aggregatorTemplates;
var fmt = $.pivotUtilities.numberFormat({suffix: " °C"});
Papa.parse("montreal_2014.csv", {
download: true,
skipEmptyLines: true,
complete: function(parsed) {
$("#output").pivotUI(parsed.data, {
hiddenAttributes: ["Date","Max Temp (C)","Mean Temp (C)", "Min Temp (C)" ,"Total Rain (mm)","Total Snow (cm)"],
derivedAttributes: {
"month name": dateFormat("Date", "%n", true),
"day name": dateFormat("Date", "%w", true)
},
rows: ["day name"],
cols: ["month name"],
sorters: {
"month name": sortAs(["Jan","Feb","Mar","Apr", "May", "Jun","Jul","Aug","Sep","Oct","Nov","Dec"]),
"day name": sortAs(["Mon","Tue","Wed", "Thu","Fri", "Sat","Sun"])
},
aggregators: {
"Mean Temperature": function() {
return tpl.average(fmt)(["Mean Temp (C)"])
},
"Max Temperature": function() {
return tpl.max(fmt)(["Max Temp (C)"])
},
"Min Temperature": function() {
return tpl.min(fmt)(["Min Temp (C)"])
}
},
renderers: $.extend( $.pivotUtilities.renderers, $.pivotUtilities.c3_renderers, $.pivotUtilities.export_renderers ),
rendererName: "Heatmap",
rendererOptions: {
heatmap: {
colorScaleGenerator: function(values) {
return d3.scale.linear()
.domain([-35, 0, 35])
.range(["#77F", "#FFF", "#F77"])
}
}
}
});
}
});
});
```
--------------------------------
### Initialize an interactive pivot table
Source: https://github.com/nicolaskruchten/pivottable/blob/master/README.md
Use the pivotUI() function to render a pivot table with a drag-and-drop interface. Requires jQueryUI to be loaded.
```javascript
$("#output").pivotUI(
[
{color: "blue", shape: "circle"},
{color: "red", shape: "triangle"}
],
{
rows: ["color"],
cols: ["shape"]
}
);
```
--------------------------------
### Input Data as Array of Arrays
Source: https://github.com/nicolaskruchten/pivottable/wiki/Input-Formats
Provide input data as an array of arrays. The first sub-array should contain attribute names. Trailing values in subsequent sub-arrays are treated as "null" if shorter than the header, and ignored if longer.
```html
```
--------------------------------
### Benchmark PivotData Performance
Source: https://github.com/nicolaskruchten/pivottable/blob/master/examples/perf.html
Uses Benchmark.js to measure the performance of PivotData initialization with different row and column groupings.
```javascript
body {font-family: Verdana;} $(function(){ $.getJSON("mps.json", function(mps) { var suite = new Benchmark.Suite; suite .add('PD: 1-cell', function() { new $.pivotUtilities.PivotData(mps, { rows: [], cols: [], aggregator: $.pivotUtilities.aggregators.Count(), filter: function(){return true;}, sorters: function(){} } ); }) .add('PD: Party, Province', function() { new $.pivotUtilities.PivotData(mps, { rows: ['Party', 'Province'], cols: [], aggregator: $.pivotUtilities.aggregators.Count(), filter: function(){return true;}, sorters: function(){} } ); }) .add('PD: Party vs Province', function() { new $.pivotUtilities.PivotData(mps, { rows: ['Party'], cols: ['Province'], aggregator: $.pivotUtilities.aggregators.Count(), filter: function(){return true;}, sorters: function(){} } ); }) .add('PD: Party, Province vs Gender, Age', function() { new $.pivotUtilities.PivotData(mps, { rows: ['Party', 'Province'], cols: ['Gender', 'Age'], aggregator: $.pivotUtilities.aggregators.Count(), filter: function(){return true;}, sorters: function(){} } ); }) .on('cycle', function(event) { $("#output").append(String(event.target)+"\n"+"\n"); }).run(); }); });
```
--------------------------------
### Input Data as Array of Objects
Source: https://github.com/nicolaskruchten/pivottable/wiki/Input-Formats
Provide input data as an array where each element is an object representing a record. Object keys are attribute names. Missing or null attributes are treated as the string "null".
```html
```
--------------------------------
### pivotUI() - Interactive Drag-and-Drop Interface
Source: https://context7.com/nicolaskruchten/pivottable/llms.txt
The `pivotUI()` function creates a fully interactive pivot table interface with drag-and-drop controls for attributes, aggregators, renderers, and filters.
```APIDOC
## pivotUI() - Interactive Drag-and-Drop Interface
### Description
Creates a complete interactive pivot table interface with drag-and-drop attribute selection, aggregator dropdown, renderer selection, and filter controls. It calls `pivot()` internally whenever the UI changes.
### Method
jQuery Plugin
### Endpoint
`$(selector).pivotUI(data, options, locale)`
### Parameters
#### Request Body (Implicit via jQuery selector and arguments)
- **data** (Array|Object|CSV|Function) - The input data for the pivot table.
- **options** (Object) - Configuration options for the pivot table. Includes all options from `pivot()` plus UI-specific settings.
- **rows** (Array) - Fields to be used as rows.
- **cols** (Array) - Fields to be used as columns.
- **vals** (Array) - Fields to be used for values.
- **aggregatorName** (String) - The name of the aggregator.
- **rendererName** (String) - The name of the renderer (e.g., "Table", "Heatmap").
- **hiddenAttributes** (Array) - Attributes hidden from all UI controls.
- **hiddenFromAggregators** (Array) - Attributes hidden from the aggregator dropdown.
- **hiddenFromDragDrop** (Array) - Attributes hidden from drag-and-drop controls.
- **exclusions** (Object) - Pre-defined exclusions for specific attributes.
- **menuLimit** (Number) - Maximum number of items in dropdown menus.
- **autoSortUnusedAttrs** (Boolean) - Automatically sort unused attributes.
- **unusedAttrsVertical** (Boolean) - Display unused attributes vertically.
- **showUI** (Boolean) - Whether to show the UI controls.
- **rendererOptions** (Object) - Options specific to the chosen renderer.
- **table** (Object) - Options for the table renderer.
- **rowTotals** (Boolean) - Show row totals.
- **colTotals** (Boolean) - Show column totals.
- **clickCallback** (Function) - Callback function when a cell is clicked.
- **onRefresh** (Function) - Callback function executed after the pivot table is refreshed.
- **locale** (String, Optional) - The locale to use for the pivot table.
### Request Example
```javascript
$.getJSON("data.json", function(data) {
$("#output").pivotUI(data, {
rows: ["Province"],
cols: ["Party"],
vals: ["Age"],
aggregatorName: "Integer Sum",
rendererName: "Heatmap",
hiddenAttributes: ["ID", "InternalCode"],
hiddenFromAggregators: ["Name", "Date"],
hiddenFromDragDrop: ["RecordID"],
exclusions: {
Province: ["Unknown", "N/A"]
},
menuLimit: 500,
autoSortUnusedAttrs: true,
unusedAttrsVertical: true,
showUI: true,
rendererOptions: {
table: {
rowTotals: true,
colTotals: true,
clickCallback: function(e, value, filters, pivotData) {
var names = [];
pivotData.forEachMatchingRecord(filters, function(record) {
names.push(record.Name);
});
alert("Records: " + names.join(", "));
}
}
},
onRefresh: function(config) {
console.log("Pivot configuration updated:", config);
}
});
});
```
### Response
(Implicitly updates the DOM element targeted by the jQuery selector with an interactive pivot table UI)
#### Success Response (200)
- The target HTML element is updated with the generated interactive pivot table UI.
#### Response Example
(No explicit JSON response, DOM manipulation occurs)
```
--------------------------------
### Load CSV Data with PapaParse and PivotTable.js
Source: https://github.com/nicolaskruchten/pivottable/blob/master/examples/mps_csv.html
Uses PapaParse to download and parse a CSV file, then initializes the pivot table with the resulting data.
```javascript
$(function(){
Papa.parse("mps.csv", {
download: true,
skipEmptyLines: true,
complete: function(parsed){
$("#output").pivotUI(parsed.data, {
rows: ["Province"],
cols: ["Party"]
});
}
});
});
```
--------------------------------
### pivot() - Static Pivot Table Rendering
Source: https://context7.com/nicolaskruchten/pivottable/llms.txt
The `pivot()` function renders a static HTML summary table into a target element. It takes data, configuration options, and an optional locale.
```APIDOC
## pivot() - Static Pivot Table Rendering
### Description
Injects an HTML summary table into the target element based on the provided data and configuration options. It accepts input data, an options object defining rows, columns, and aggregation, and an optional locale parameter.
### Method
jQuery Plugin
### Endpoint
`$(selector).pivot(data, options, locale)`
### Parameters
#### Request Body (Implicit via jQuery selector and arguments)
- **data** (Array|Object|CSV|Function) - The input data for the pivot table.
- **options** (Object) - Configuration options for the pivot table, including rows, columns, aggregator, filters, derived attributes, and sorters.
- **rows** (Array) - Fields to be used as rows.
- **cols** (Array) - Fields to be used as columns.
- **aggregator** (Object) - The aggregation function to apply.
- **aggregatorName** (String) - The name of the aggregator.
- **rowOrder** (String) - Order of rows.
- **colOrder** (String) - Order of columns.
- **filter** (Function) - A function to filter records.
- **derivedAttributes** (Object) - An object defining custom derived attributes.
- **sorters** (Object) - An object defining custom sorting for fields.
- **locale** (String, Optional) - The locale to use for the pivot table.
### Request Example
```javascript
// Basic usage with array of objects
$("#output").pivot(
[
{color: "blue", shape: "circle", size: 10},
{color: "red", shape: "triangle", size: 15},
{color: "blue", shape: "square", size: 20},
{color: "red", shape: "circle", size: 25}
],
{
rows: ["color"],
cols: ["shape"],
aggregator: $.pivotUtilities.aggregators["Sum"](["size"]),
aggregatorName: "Sum",
rowOrder: "key_a_to_z",
colOrder: "key_a_to_z"
}
);
// With custom filtering and derived attributes
$("#output").pivot(salesData, {
rows: ["Region", "Category"],
cols: ["Quarter"],
aggregator: $.pivotUtilities.aggregators["Average"](["Revenue"]),
filter: function(record) {
return record.Revenue > 1000;
},
derivedAttributes: {
"Profit Margin": function(record) {
return ((record.Revenue - record.Cost) / record.Revenue * 100).toFixed(1) + "%";
}
},
sorters: {
Quarter: $.pivotUtilities.sortAs(["Q1", "Q2", "Q3", "Q4"])
}
});
```
### Response
(Implicitly updates the DOM element targeted by the jQuery selector)
#### Success Response (200)
- The target HTML element is updated with the generated pivot table.
#### Response Example
(No explicit JSON response, DOM manipulation occurs)
```
--------------------------------
### Capture PivotTable configuration with onRefresh
Source: https://github.com/nicolaskruchten/pivottable/blob/master/examples/onrefresh.html
Uses the onRefresh callback to stringify the current configuration object. Non-serializable functions and bulky default properties are removed before outputting to a textarea.
```javascript
$(function(){
$.getJSON("mps.json", function(mps) {
$("#output2").pivotUI(mps, {
onRefresh: function(config) {
var config_copy = JSON.parse(JSON.stringify(config));
//delete some values which are functions
delete config_copy["aggregators"];
delete config_copy["renderers"];
//delete some bulky default values
delete config_copy["rendererOptions"];
delete config_copy["localeStrings"];
$("#output").text(JSON.stringify(config_copy, undefined, 2));
}
});
});
});
```