Skip to content
Projects

About

light and fast implementation of web pivot table / pivot chart components.

Data & Analytics

How these counts are measured

What you can do

  • basic expandable nest/cross table
  • custom aggregator of measures
  • different visualization type

Measured star growth

in 24h
0
in 7 days
Collecting history
in 15 days
Collecting history
in 1 month
Collecting history

Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.

README.md

Original

English | 简体中文

Pivot-Chart

Pivot-Chart is a comprehensive data visualization tool that enhances pivot tables with visualizations and charts, offering a more intuitive and informative way to analyze your data. With Pivot-Chart, you can elevate your data analysis and take a new approach to exploring your data. Unlike other pivot-table + vis solution, pivot chart retains nest multi-level aggregation feature of pivot table, which allows you to compare between different aggregation levels and make it easier to drill down and roll up.

Integrating Pivot-Chart into your data applications is easy, simply import the npm package.

While this is a proof-of-concept project, your feedback and suggestions are valued and appreciated.

pivot-chart also provide with basic pivot table components for you to build your web apps, you can regard pivot table as a member in the subset of pivot charts.

Demo

Online Demo

Features

feature demo(gif)
basic expandable nest/cross table basic expandable nest/cross table.gif
custom aggregator of measures ustom aggregator of measures.gif
different visualization type different visualization type.gif

Usage

Install the package in your application.

npm install pivot-chart


basic usage.

import { PivotChart } from 'pivot-chart';

function App () {
  return <PivotChart
    visType={visType}
    dataSource={data}
    rows={rows}
    columns={columns}
    measures={measures} 
    />
}

Upgrading to 1.0

  • Applications need React and React DOM 19.2 or newer in the 19.x line, plus styled-components 6.7 or newer in the 6.x line.
  • The package ships as ESM. Import public components and types from pivot-chart. Command-line tooling requires Node.js 22.12 or newer.
  • Use createRoot at the application entry point and enable the automatic JSX transform.

Local development

npm ci
npm run dev
npm run typecheck
npm run build
npm run build:demo

Open http://localhost:1996 for the development demo. The library builds to packages/react-pivot-table/build, and the demo builds to packages/react-pivot-table/dist. Run npm run preview to serve the built demo.

API

Types

Type Desc
Field
- id 
- name 
- aggName  aggregator's name.
- cmp <(a: any, b: any) => number>
Measure extends Field
- aggregator aggregator function.
- minWidth 
- formatter <value: number> => number
VisType currently support number , bar , line , scatter .
Record a plain javascript object
DataSource Record[] , Array of Record.
QueryNode
- dimCode 
- dimValue 
QueryPath <QueryNode[]>.
example: [{dimCode: 'Sex', dimValue: 'male'}, {dimCode: 'Age', dimValue:'*'}]

common

common interface are those used in both async pivot table and sync pivot table.

  • rows: Field[] dimensions in row. required
  • columns: Field[] dimensions in column.required
  • measures: Measure[] measures or indicators.required
  • visType: VisType mark type in cell. number as default(which is a common pivot table).optional
  • defaultExpandedDepth. default expanded level in row or column nest tree.optional
    • defaultExpandedDepth.rowDepth: number 
    • defaultExpandedDepth.columnDepth: number

     

  • showAggregatedNode: {row: boolean; column: boolean} whether display aggregated node for each group. optional

SyncPivotTable

  • dataSource: Record[] . Array of record(normaly plain object). (json style data array). required

example:
import { useState, useMemo } from 'react';
import { createRoot } from 'react-dom/client';
import { getTitanicData } from './mock';
import { ToolBar, PivotChart, DragableFields, Aggregators } from 'pivot-chart';
import type { AggNodeConfig, DraggableFieldState, VisType } from 'pivot-chart';

const { dataSource, dimensions, measures } = getTitanicData();
const fields = dimensions.concat(measures).map(f => ({ id: f, name: f }));

const initDraggableState: DraggableFieldState = {
  fields: [],
  rows: [],
  columns: [],
  measures: []
};

function App () {
  const [fstate, setFstate] = useState<DraggableFieldState>(initDraggableState)
  const [visType, setVisType] = useState<VisType>('number');
  const [aggNodeConfig, setAggNodeConfig] = useState<AggNodeConfig>({ row: false, column: false });
  const measures = useMemo(() => fstate['measures'].map(f => ({
    ...f,
    aggregator: Aggregators[(f.aggName || 'sum') as keyof typeof Aggregators]
  })), [fstate['measures']]);
  return <div>
    <DragableFields onStateChange={(state) => {setFstate(state)}} fields={fields} />
    <ToolBar
      visType={visType}
      onVisTypeChange={setVisType}
      showAggregatedNode={aggNodeConfig}
      onShowAggNodeChange={setAggNodeConfig}
    />
    <PivotChart visType={visType} dataSource={dataSource} rows={fstate['rows']} columns={fstate['columns']} measures={measures} showAggregatedNode={aggNodeConfig} />
  </div>
}

createRoot(document.getElementById('root')!).render(<App />);

AsyncPivotTable (WIP)

  • cubeQuery: (path: QueryPath, measures: string[]) => Promise; . A function handle for cube query. path is the groupby dimension path(made of a series of dimension and its value). measures are the fields needed to be aggregated. required
  • branchFilter: bad api, not recommanded to use it. a fake filter whihc only control display of node and not influence the aggregated result of parent node. optional
  • dimensionCompare: (a: string, b: string) => number .compare function for sort of dimension node. optional
import { useCallback, useMemo, useState } from 'react';
import { Aggregators, AsyncPivotChart, DragableFields, ToolBar } from 'pivot-chart';
import type { AggNodeConfig, DraggableFieldState, Utils, VisType } from 'pivot-chart';
import { getTitanicData } from './mock';
import { TitanicCubeService } from './service';

const { dimensions, measures: measureFields } = getTitanicData();
const fields = [...dimensions, ...measureFields].map(id => ({ id, name: id }));

function AsyncApp() {
  const [fieldState, setFieldState] = useState<DraggableFieldState>({
    fields: [],
    rows: [],
    columns: [],
    measures: [],
  });
  const [visType, setVisType] = useState<VisType>('number');
  const [aggNodeConfig, setAggNodeConfig] = useState<AggNodeConfig>({ row: false, column: false });
  const measures = useMemo(() => fieldState.measures.map(field => ({
    ...field,
    aggregator: Aggregators[(field.aggName || 'sum') as keyof typeof Aggregators],
    minWidth: 100,
    formatter: field.id === 'Survived' ? (value: number | undefined) => `${value} *` : undefined,
  })), [fieldState.measures]);
  const cubeQuery = useCallback((path: Utils.QueryPath, measureIds: string[]) => {
    const ops = measureIds.map(id => measures.find(measure => measure.id === id)?.aggName || 'sum');
    return TitanicCubeService(path.map(node => node.dimCode), measureIds, ops);
  }, [measures]);

  return (
    <div>
      <DragableFields onStateChange={setFieldState} fields={fields} />
      <ToolBar
        visType={visType}
        onVisTypeChange={setVisType}
        showAggregatedNode={aggNodeConfig}
        onShowAggNodeChange={setAggNodeConfig}
      />
      <AsyncPivotChart
        visType={visType}
        rows={fieldState.rows}
        columns={fieldState.columns}
        defaultExpandedDepth={{ rowDepth: 20, columnDepth: 20 }}
        showAggregatedNode={aggNodeConfig}
        cubeQuery={cubeQuery}
        measures={measures}
      />
    </div>
  );
}

Theme

  • Theme.registerTheme(theme: ThemeConfig)
  • ThemeConfig

 

interface ThemeConfig {
  root?: {
    display?: boolean,
    label?: string
  },
  summary?: {
    label?: string
  },
  table?: {
    thead?: {
      backgroundColor?: string;
      color?: string;
    }
    borderColor?: string;
    color?: string;
  }
}
// default config
const THEME_CONFIG: ThemeConfig = {
  root: {
    display: true,
    label: 'All'
  },
  summary: {
    label: '(total)'
  },
  table: {
    thead: {
      backgroundColor: '#E9EDF2',
      color: '#5A6C84'
    },
    borderColor: '#DFE3E8',
    color: '#333333'
  }
};
import { useState, useMemo } from 'react';
import { createRoot } from 'react-dom/client';
import { getTitanicData } from './mock';
import { ToolBar, PivotChart, DragableFields, Aggregators, Theme } from 'pivot-chart';
import type { AggNodeConfig, DraggableFieldState, VisType } from 'pivot-chart';

const { dataSource, dimensions, measures } = getTitanicData();
const fields = dimensions.concat(measures).map(f => ({ id: f, name: f }));

const initDraggableState: DraggableFieldState = {
  fields: [],
  rows: [],
  columns: [],
  measures: []
};

Theme.registerTheme({
  root: {
    display: true,
    label: 'root'
  },
  summary: {
    label: '(total)'
  }
})

function App () {
  const [fstate, setFstate] = useState<DraggableFieldState>(initDraggableState)
  const [visType, setVisType] = useState<VisType>('number');
  const [aggNodeConfig, setAggNodeConfig] = useState<AggNodeConfig>({ row: false, column: false });
  const measures = useMemo(() => fstate['measures'].map(f => ({
    ...f,
    aggregator: Aggregators[(f.aggName || 'sum') as keyof typeof Aggregators]
  })), [fstate['measures']]);
  return <div>
    <DragableFields onStateChange={(state) => {setFstate(state)}} fields={fields} />
    <ToolBar
      visType={visType}
      onVisTypeChange={setVisType}
      showAggregatedNode={aggNodeConfig}
      onShowAggNodeChange={setAggNodeConfig}
    />
    <PivotChart visType={visType} dataSource={dataSource} rows={fstate['rows']} columns={fstate['columns']} measures={measures} showAggregatedNode={aggNodeConfig} />
  </div>
}

createRoot(document.getElementById('root')!).render(<App />);

Common Question

SyncPivotChart vs. AsyncPivotChart ?

Sync Pivot Chart does all cube computaion in frontend.(In future, it may do those work in webworker and it will seems to be async).
Async Pivot Chart can use cube query from server or customed implementation(either on server or browser, async or sync), but developer need to figure out how to speed up those by themsleves.

Explore related projects

Loading…