dc.js - Dimensional Charting Javascript Library v

dc.js is a javascript charting library with native crossfilter support and allowing highly efficient exploration on large multi-dimensional dataset (inspired by crossfilter's demo). It leverages d3 engine to render charts in css friendly svg format. Charts rendered using dc.js are naturally data driven and reactive therefore providing instant feedback on user's interaction. The main objective of this project is to provide an easy yet powerful javascript library which can be utilized to perform data visualization and analysis in browser as well as on mobile device. This example page is forked from https://github.com/NickQiZhu/dc.js and for more information please check out original Wiki and API Reference. For your questions and answers please try dc.js user group.

The following charts provide a live example of dc.js used against Shanghai SSE Composite Index (000001.SS) for the last 23 years. (You can run this example completely off-line). Although it is just an example, using it you can already ask some quite interesting questions. If I am going to gamble whether Shanghai SSE Composite Index will gain or lose tomorrow what is my chance? Is Friday or Monday the most unlucky day for investors? Is spring better than winter to invest? Can you find the outliers? When did the outliers occur? Public data source money.163.com.

Try it out or checkout other examples.

Shanghai SSE Composite Index 1990/12/19-2013/05/22

Yearly Performance (x: index gain, y: index gain(%), radius: fluctuation/index ratio, color: gain/loss)
Days by Gain/Loss
Quarters
Day of Week
Days by Fluctuation(%)
Monthly Index Abs Move & Volume/500,000 Chart (Blue Line: Avg Index, Green Line: Index Fluctuation)

select a time range to zoom in

selected out of records | Reset All
Date Open Close Change Volume

Quick 5 Mins How-To Guide (API Reference)

Load your data

            /*
             * data can be loaded through regular means with your
             * favorite javascript library
             */
            d3.csv("data.csv", function(data) {...};
            d3.json("data.json", function(data) {...};
            jQuery.getJson("data.json", function(data){...});
        

Generate dimension and group

        // since its a csv file we need to format the data a bit
        var dateFormat = d3.time.format("%m/%d/%Y");
        data.forEach(function(e) { e.dd = dateFormat.parse(e.date); });

        // feed it through crossfilter
        var ndx = crossfilter(data);

        // define group all for counting
        var all = ndx.groupAll();

        // define a dimension
        var volumeByMonth = ndx.dimension(function(d) { return d3.time.month(d.dd); });
        // map/reduce to group sum
        var volumeByMonthGroup = volumeByMonth.group().reduceSum(function(d) { return d.volume; });
    

Anchor Div for Charts

        
        
Days by Gain or Loss

Pie/Donut Chart

        /* Create a pie chart and use the given css selector as anchor. You can also specify
         * an optional chart group for this chart to be scoped within. When a chart belongs
         * to a specific group then any interaction with such chart will only trigger redraw
         * on other charts within the same chart group. */
        dc.pieChart("#gain-loss-chart", "chartGroup")
            .width(200) // (optional) define chart width, :default = 200
            .height(200) // (optional) define chart height, :default = 200
            .transitionDuration(500) // (optional) define chart transition duration, :default = 350
            // (optional) define color array for slices
            .colors(['#3182bd', '#6baed6', '#9ecae1', '#c6dbef', '#dadaeb'])
            // (optional) define color domain to match your data domain if you want to bind data or color
            .colorDomain([-1750, 1644])
            // (optional) define color value accessor
            .colorAccessor(function(d, i){return d.value;})
            .radius(90) // define pie radius
            // (optional) if inner radius is used then a donut chart will
            // be generated instead of pie chart
            .innerRadius(40)
            .dimension(gainOrLoss) // set dimension
            .group(gainOrLossGroup) // set group
            // (optional) by default pie chart will use group.key as it's label
            // but you can overwrite it with a closure
            .label(function(d) { return d.data.key + "(" + Math.floor(d.data.value / all.value() * 100) + "%)"; })
            // (optional) whether chart should render labels, :default = true
            .renderLabel(true)
            // (optional) by default pie chart will use group.key and group.value as its title
            // you can overwrite it with a closure
            .title(function(d) { return d.data.key + "(" + Math.floor(d.data.value / all.value() * 100) + "%)"; })
            // (optional) whether chart should render titles, :default = false
            .renderTitle(true);
    

Bar Chart

        /* Create a bar chart and use the given css selector as anchor. You can also specify
         * an optional chart group for this chart to be scoped within. When a chart belongs
         * to a specific group then any interaction with such chart will only trigger redraw
         * on other charts within the same chart group. */
        dc.barChart("#volume-month-chart")
            .width(990) // (optional) define chart width, :default = 200
            .height(250) // (optional) define chart height, :default = 200
            .transitionDuration(500) // (optional) define chart transition duration, :default = 500
            // (optional) define margins
            .margins({top: 10, right: 50, bottom: 30, left: 40})
            .dimension(volumeByMonth) // set dimension
            .group(volumeByMonthGroup) // set group
            // (optional) whether chart should rescale y axis to fit data, :default = false
            .elasticY(true)
            // (optional) when elasticY is on whether padding should be applied to y axis domain, :default=0
            .yAxisPadding(100)
            // (optional) whether chart should rescale x axis to fit data, :default = false
            .elasticX(true)
            // (optional) when elasticX is on whether padding should be applied to x axis domain, :default=0
            .xAxisPadding(500)
            // define x scale
            .x(d3.time.scale().domain([new Date(1990, 12, 1), new Date(2013, 5, 31)]))
            // (optional) set filter brush rounding
            .round(d3.time.month.round)
            // define x axis units
            .xUnits(d3.time.months)
            // (optional) whether bar should be center to its x value, :default=false
            .centerBar(true)
            // (optional) set gap between bars manually in px, :default=2
            .barGap(1)
            // (optional) render horizontal grid lines, :default=false
            .renderHorizontalGridLines(true)
            // (optional) render vertical grid lines, :default=false
            .renderVerticalGridLines(true)
            // (optional) add stacked group and custom value retriever
            .stack(monthlyMoveGroup, function(d){return d.value;})
            // (optional) you can add multiple stacked group with or without custom value retriever
            // if no custom retriever provided base chart's value retriever will be used
            .stack(monthlyMoveGroup)
            // (optional) whether this chart should generate user interactive brush to allow range
            // selection, :default=true.
            .brushOn(true)
            // (optional) whether svg title element(tooltip) should be generated for each bar using
            // the given function, :default=no
            .title(function(d) { return "Value: " + d.value; })
            // (optional) whether chart should render titles, :default = false
            .renderTitle(true);
    

Row Chart

        /* Create a row chart and use the given css selector as anchor. You can also specify
         * an optional chart group for this chart to be scoped within. When a chart belongs
         * to a specific group then any interaction with such chart will only trigger redraw
         * on other charts within the same chart group. */
        dc.rowChart("#days-of-week-chart", "chartGroup")
            .width(180) // (optional) define chart width, :default = 200
            .height(180) // (optional) define chart height, :default = 200
            .group(dayOfWeekGroup) // set group
            .dimension(dayOfWeek) // set dimension
            // (optional) define margins
            .margins({top: 20, left: 10, right: 10, bottom: 20})
            // (optional) define color array for slices
            .colors(['#3182bd', '#6baed6', '#9ecae1', '#c6dbef', '#dadaeb'])
            // (optional) set gap between rows, default is 5
            gap(7)
            // (optional) set x offset for labels, default is 10
            labelOffSetX(5)
            // (optional) set y offset for labels, default is 15
            labelOffSetY(10)
            // (optional) whether chart should render labels, :default = true
            .renderLabel(true)
            // (optional) by default pie chart will use group.key and group.value as its title
            // you can overwrite it with a closure
            .title(function(d) { return d.data.key + "(" + Math.floor(d.data.value / all.value() * 100) + "%)"; })
            // (optional) whether chart should render titles, :default = false
            .renderTitle(true);
            // (optional) specify the number of ticks for the X axis
            .xAxis().ticks(4);
    

Line Chart

        /* Create a line chart and use the given css selector as anchor. You can also specify
         * an optional chart group for this chart to be scoped within. When a chart belongs
         * to a specific group then any interaction with such chart will only trigger redraw
         * on other charts within the same chart group. */
        dc.lineChart("#monthly-move-chart", "chartGroup")
            .width(990) // (optional) define chart width, :default = 200
            .height(200) // (optional) define chart height, :default = 200
            .transitionDuration(500) // (optional) define chart transition duration, :default = 500
            // (optional) define margins
            .margins({top: 10, right: 50, bottom: 30, left: 40})
            .dimension(monthlyMove) // set dimension
            .group(monthlyMoveGroup) // set group
            // (optional) whether chart should rescale y axis to fit data, :default = false
            .elasticY(true)
            // (optional) when elasticY is on whether padding should be applied to y axis domain, :default=0
            .yAxisPadding(100)
            // (optional) whether chart should rescale x axis to fit data, :default = false
            .elasticX(true)
            // (optional) when elasticX is on whether padding should be applied to x axis domain, :default=0
            .xAxisPadding(500)
            // define x scale
            .x(d3.time.scale().domain([new Date(1985, 0, 1), new Date(2013, 11, 31)]))
            // (optional) set filter brush rounding
            .round(d3.time.month.round)
            // define x axis units
            .xUnits(d3.time.months)
            // (optional) render horizontal grid lines, :default=false
            .renderHorizontalGridLines(true)
            // (optional) render vertical grid lines, :default=false
            .renderVerticalGridLines(true)
            // (optional) render as area chart, :default = false
            .renderArea(true)
            // (optional) add stacked group and custom value retriever
            .stack(monthlyMoveGroup, function(d){return d.value;})
            // (optional) you can add multiple stacked group with or without custom value retriever
            // if no custom retriever provided base chart's value retriever will be used
            .stack(monthlyMoveGroup)
            // (optional) whether this chart should generate user interactive brush to allow range
            // selection, :default=true.
            .brushOn(true)
            // (optional) whether dot and title should be generated on the line using
            // the given function, :default=no
            .title(function(d) { return "Value: " + d.value; })
            // (optional) whether chart should render titles, :default = false
            .renderTitle(true)
            // (optional) radius used to generate title dot, :default = 5
            .dotRadius(10);
    

Composite Chart

    /* Create a composite chart and use the given css selector as anchor. You can also specify
         * an optional chart group for this chart to be scoped within. When a chart belongs
         * to a specific group then any interaction with such chart will only trigger redraw
         * on other charts within the same chart group. */
    dc.compositeChart("#montly-move-chart", "chartGroup")
        .width(990) // (optional) define chart width, :default = 200
        .height(200) // (optional) define chart height, :default = 200
        .transitionDuration(500) // (optional) define chart transition duration, :default = 500
        // (optional) define margins
        .margins({top: 10, right: 50, bottom: 30, left: 40})
        .dimension(monthlyMove) // set dimension
        .group(monthlyMoveGroup) // set group
        // (optional) whether chart should rescale y axis to fit data, :default = false
        .elasticY(true)
        // (optional) when elasticY is on whether padding should be applied to y axis domain, :default=0
        .yAxisPadding(100)
        // (optional) whether chart should rescale x axis to fit data, :default = false
        .elasticX(true)
        // (optional) when elasticX is on whether padding should be applied to x axis domain, :default=0
        .xAxisPadding(500)
        // define x scale
        .x(d3.time.scale().domain([new Date(1985, 0, 1), new Date(2013, 11, 31)]))
        // (optional) set filter brush rounding
        .round(d3.time.month.round)
        // define x axis units
        .xUnits(d3.time.months)
        // (optional) render horizontal grid lines, :default=false
        .renderHorizontalGridLines(true)
        // (optional) render vertical grid lines, :default=false
        .renderVerticalGridLines(true)
        // compose sub charts, currently composite chart only supports line chart & bar chart
        .compose([
            /* Pass the parent chart instance to sub-chart function instead of css selector.
             * Sub-charts can have it's own group and dimension however usually it should
             * share parent chart's dimension. If sub-chart's dimension or group is not
             * explicitly defined here then it will simply inherent from it's parent. */
            dc.barChart(volumeMoveChart).group(volumeByMonthGroup),
            // you can even include stacked bar chart or line chart in a composite chart
            dc.lineChart(volumeMoveChart).group(indexAvgByMonthGroup).valueAccessor(function(d){return d.value.avg;}).renderArea(true).stack(monthlyMoveGroup, function(d){return d.value;})
        ])
        // (optional) whether this chart should generate user interactive brush to allow range
        // selection, :default=true.
        .brushOn(true);

Bubble Chart

        /* Create a bubble chart and use the given css selector as anchor. You can also specify
         * an optional chart group for this chart to be scoped within. When a chart belongs
         * to a specific group then any interaction with such chart will only trigger redraw
         * on other charts within the same chart group. */
        dc.bubbleChart("#yearly-bubble-chart", "chartGroup")
            .width(990) // (optional) define chart width, :default = 200
            .height(250) // (optional) define chart height, :default = 200
            .transitionDuration(1000) // (optional) define chart transition duration, :default = 1000
            // (optional) define margins
            .margins({top: 10, right: 50, bottom: 30, left: 40})
            .dimension(yearlyDimension) // set dimension
            /* Bubble chart expect the groups are reduced to multiple values which would then be used
             * to generate x, y, and radius for each key (bubble) in the group */
            .group(yearlyPerformanceGroup)
            // (optional) define color function or array for bubbles
            .colors(["red", "#ccc","steelblue","green"])
            // (optional) define color domain to match your data domain if you want to bind data or color
            .colorDomain([-1750, 1644])
            // (optional) define color value accessor
            .colorAccessor(function(d, i){return d.value.absGain;})
            // closure used to retrieve x value from multi-value group
            .keyAccessor(function(p) {return p.value.absGain;})
            // closure used to retrieve y value from multi-value group
            .valueAccessor(function(p) {return p.value.percentageGain;})
            // closure used to retrieve radius value from multi-value group
            .radiusValueAccessor(function(p) {return p.value.fluctuationPercentage;})
            // set x scale
            .x(d3.scale.linear().domain([-2500, 2500]))
            // set y scale
            .y(d3.scale.linear().domain([-100, 100]))
            // (optional) whether chart should rescale y axis to fit data, :default = false
            .elasticY(true)
            // (optional) when elasticY is on whether padding should be applied to y axis domain, :default=0
            .yAxisPadding(100)
            // (optional) whether chart should rescale x axis to fit data, :default = false
            .elasticX(true)
            // (optional) when elasticX is on whether padding should be applied to x axis domain, :default=0
            .xAxisPadding(500)
            // set radius scale
            .r(d3.scale.linear().domain([0, 4000]))
            // (optional) whether chart should render labels, :default = true
            .renderLabel(true)
            // (optional) closure to generate label per bubble, :default = group.key
            .label(function(p) {return p.key.getFullYear();})
            // (optional) whether chart should render titles, :default = false
            .renderTitle(true)
            // (optional) closure to generate title per bubble, :default = d.key + ": " + d.value
            .title(function(p) {
                return p.key.getFullYear()
                        + "\n"
                        + "Index Gain: " + numberFormat(p.value.absGain) + "\n"
                        + "Index Gain in Percentage: " + numberFormat(p.value.percentageGain) + "%\n"
                        + "Fluctuation / Index Ratio: " + numberFormat(p.value.fluctuationPercentage) + "%";
            })
            // (optional) render horizontal grid lines, :default=false
            .renderHorizontalGridLines(true)
            // (optional) render vertical grid lines, :default=false
            .renderVerticalGridLines(true);
    

Geo Choropleth Chart

    /* Create a choropleth chart and use the given css selector as anchor. You can also specify
     * an optional chart group for this chart to be scoped within. When a chart belongs
     * to a specific group then any interaction with such chart will only trigger redraw
     * on other charts within the same chart group. */
    dc.geoChoroplethChart("#us-chart")
        .width(990) // (optional) define chart width, :default = 200
        .height(500) // (optional) define chart height, :default = 200
        .transitionDuration(1000) // (optional) define chart transition duration, :default = 1000
        .dimension(states) // set crossfilter dimension, dimension key should match the name retrieved in geo json layer
        .group(stateRaisedSum) // set crossfilter group
        // (optional) define color function or array for bubbles
        .colors(["#ccc", "#E2F2FF","#C4E4FF","#9ED2FF","#81C5FF","#6BBAFF","#51AEFF","#36A2FF","#1E96FF","#0089FF","#0061B5"])
        // (optional) define color domain to match your data domain if you want to bind data or color
        .colorDomain([-5, 200])
        // (optional) define color value accessor
        .colorAccessor(function(d, i){return d.value;})
        /* Project the given geojson. You can call this function mutliple times with different geojson feed to generate
         * multiple layers of geo paths.
         * 1st param - geo json data
         * 2nd param - name of the layer which will be used to generate css class
         * 3rd param - (optional) a function used to generate key for geo path, it should match the dimension key
         * in order for the coloring to work properly */
        .overlayGeoJson(statesJson.features, "state", function(d) {
            return d.properties.name;
        })
        // (optional) closure to generate title for path, :default = d.key + ": " + d.value
        .title(function(d) {
            return "State: " + d.key + "\nTotal Amount Raised: " + numberFormat(d.value ? d.value : 0) + "M";
        });

Bubble Overlay Chart

    /* Create a overlay bubble chart and use the given css selector as anchor. You can also specify
     * an optional chart group for this chart to be scoped within. When a chart belongs
     * to a specific group then any interaction with such chart will only trigger redraw
     * on other charts within the same chart group. */
    dc.bubbleOverlay("#bubble-overlay")
        // bubble overlay chart does not generate it's own svg element but rather resue an existing
        // svg to generate it's overlay layer
        .svg(d3.select("#bubble-overlay svg"))
        .width(990) // (optional) define chart width, :default = 200
        .height(500) // (optional) define chart height, :default = 200
        .transitionDuration(1000) // (optional) define chart transition duration, :default = 1000
        .dimension(states) // set crossfilter dimension, dimension key should match the name retrieved in geo json layer
        .group(stateRaisedSum) // set crossfilter group
        // closure used to retrieve x value from multi-value group
        .keyAccessor(function(p) {return p.value.absGain;})
        // closure used to retrieve y value from multi-value group
        .valueAccessor(function(p) {return p.value.percentageGain;})
        // (optional) define color function or array for bubbles
        .colors(["#ccc", "#E2F2FF","#C4E4FF","#9ED2FF","#81C5FF","#6BBAFF","#51AEFF","#36A2FF","#1E96FF","#0089FF","#0061B5"])
        // (optional) define color domain to match your data domain if you want to bind data or color
        .colorDomain([-5, 200])
        // (optional) define color value accessor
        .colorAccessor(function(d, i){return d.value;})
        // closure used to retrieve radius value from multi-value group
        .radiusValueAccessor(function(p) {return p.value.fluctuationPercentage;})
        // set radius scale
        .r(d3.scale.linear().domain([0, 3]))
        // (optional) whether chart should render labels, :default = true
        .renderLabel(true)
        // (optional) closure to generate label per bubble, :default = group.key
        .label(function(p) {return p.key.getFullYear();})
        // (optional) whether chart should render titles, :default = false
        .renderTitle(true)
        // (optional) closure to generate title per bubble, :default = d.key + ": " + d.value
        .title(function(d) {
            return "Title: " + d.key;
        })
        // add data point to it's layer dimension key that matches point name will be used to
        // generate bubble. multiple data points can be added to bubble overlay to generate
        // multiple bubbles
        .point("California", 100, 120)
        .point("Colorado", 300, 120)
        // (optional) setting debug flag to true will generate a transparent layer on top of
        // bubble overlay which can be used to obtain relative x,y coordinate for specific
        // data point, :default = false
        .debug(true);

Data Table

        
        
Date Open Close Change Volume
        /* Create a data table widget and use the given css selector as anchor. You can also specify
         * an optional chart group for this chart to be scoped within. When a chart belongs
         * to a specific group then any interaction with such chart will only trigger redraw
         * on other charts within the same chart group. */
        dc.dataTable("#data-table")
            // set dimension
            .dimension(dateDimension)
            // data table does not use crossfilter group but rather a closure
            // as a grouping function
            .group(function(d) {
                return d.dd.getFullYear() + "/" + (d.dd.getMonth() + 1);
            })
            // (optional) max number of records to be shown, :default = 25
            .size(10)
            // dynamic columns creation using an array of closures
            .columns([
                function(d) { return d.date; },
                function(d) { return d.open; },
                function(d) { return d.close; },
                function(d) { return Math.floor((d.close - d.open)/d.open*100) + "%"; },
                function(d) { return d.volume; }
            ])
            // (optional) sort using the given field, :default = function(d){return d;}
            .sortBy(function(d){ return d.dd; })
            // (optional) sort order, :default ascending
            .order(d3.ascending);
    

Data Count

        
selected out of records
        /* Create a data count widget and use the given css selector as anchor. You can also specify
         * an optional chart group for this chart to be scoped within. When a chart belongs
         * to a specific group then any interaction with such chart will only trigger redraw
         * on other charts within the same chart group. */
        dc.dataCount("#data-count")
            .dimension(ndx) // set dimension to all data
            .group(all); // set group to ndx.groupAll()
    

Rendering

        // simply call renderAll() to render all charts on the page
        dc.renderAll();
        // or you can render charts belong to a specific chart group
        dc.renderAll("group");

        // once rendered you can call redrawAll to update charts incrementally when data
        // change without re-rendering everything
        dc.redrawAll();
        // or you can choose to redraw only those charts associated with a specific chart group
        dc.redrawAll("group");
    

Try dc.js with your own data set and have fun!

Fork me on GitHub