### Start dc.js Development Server Source: https://github.com/dc-js/dc.js/blob/develop/README.md Launch the local development server to view examples and run Jasmine specs. Access specs at http://localhost:8888/spec and examples at http://localhost:8888/web. ```bash $ grunt server ``` -------------------------------- ### Install dc.js Dependencies Source: https://github.com/dc-js/dc.js/blob/develop/README.md Install the necessary Node.js modules for building dc.js locally. Ensure Node.js and npm are installed. ```bash $ npm install ``` -------------------------------- ### Initialize dc.js Charts and Load Data Source: https://github.com/dc-js/dc.js/blob/develop/web-src/examples/table-pagination.html Sets up a dc.js DataTable and PieChart, then loads data from a CSV file to initialize a crossfilter instance. This is the initial setup for the example. ```javascript var chart = new dc.DataTable("#test"); var piechart = new dc.PieChart("#piechart"); var ndx; d3.csv("morley.csv").then(function(experiments) { ndx = crossfilter(experiments); var fmt = d3.format('02d'); var runDimension = ndx.dimension(function(d) {return [fmt(+d.Expt),fmt(+d.Run)];}), experimentDimension = ndx.dimension(function(d) {return d.Expt;}), experimentGroup = experimentDimension.group().reduceCount(); piechart.width(300).height(280) .innerRadius(100).externalLabels(50).externalRadiusPadding(50).drawPaths(true) .dimension(experimentDimension).group(experimentGroup) .legend(dc.legend()) .controlsUseVisibility(true); chart .width(300) .height(480) .dimension(runDimension) .size(Infinity) .showSections(false) .columns([ 'Expt', 'Run', 'Speed' ]) .sortBy(function (d) { return [fmt(+d.Expt),fmt(+d.Run)]; }) .order(d3.ascending) .on('preRender', update_offset) .on('preRedraw', update_offset) .on('pretransition', display); dc.renderAll(); }); ``` -------------------------------- ### Install dc.js with npm Source: https://github.com/dc-js/dc.js/blob/develop/README.md Install the dc.js package using npm for use in Node.js projects or with module bundlers. ```bash npm install dc ``` -------------------------------- ### Logger Warning Example Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Put a warning message to the console. This example demonstrates logging a warning. ```javascript logger.warn('Invalid use of .tension on CurveLinear'); ``` -------------------------------- ### Logger Debug Log Example Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Enable debug level logging. Set to `false` by default. This example shows how to log a debug message. ```javascript logger.debug('Total number of slices: ' + numSlices); ``` -------------------------------- ### DataGrid.beginSlice Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Sets or gets the starting index for displayed entries, useful for pagination. ```APIDOC ## dataGrid.beginSlice([beginSlice]) ⇒ Number | DataGrid ### Description Get or set the index of the beginning slice which determines which entries get displayed by the widget. Useful when implementing pagination. ### Parameters #### Path Parameters - **[beginSlice]** (Number) - Default: 0 ``` -------------------------------- ### Logger Warn Once Example Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Put a warning message to the console that will only appear once for unique messages. This example shows how to log a unique warning. ```javascript logger.warnOnce('Invalid use of .tension on CurveLinear'); ``` -------------------------------- ### SelectMenu.order Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Set or get the order of the options in the select menu. ```APIDOC ## SelectMenu.order([order]) ### Description Set or get the order of the options in the select menu. ### Method GET/SET ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **[order]** (function) - A function that defines the order of the options. It takes two arguments (a, b) and should return a negative value if a < b, a positive value if a > b, and 0 if they are equal. ### Request Example ```javascript // Get var orderFunc = selectMenu.order(); // Set selectMenu.order(function(a, b) { return a.key.localeCompare(b.key); }); ``` ``` -------------------------------- ### transition Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Starts a D3 transition on a selection if transitions are enabled and duration is positive. ```APIDOC ## transition(selection, [duration], [delay], [name]) ⇒ d3.transition | d3.selection ### Description Start a transition on a selection if transitions are globally enabled ([disableTransitions](disableTransitions) is false) and the duration is greater than zero; otherwise return the selection. Since most operations are the same on a d3 selection and a d3 transition, this allows a common code path for both cases. ### Parameters #### Path Parameters - **selection** (d3.selection) - Required - The selection to be transitioned - **duration** (Number | function) - Optional - The duration of the transition in milliseconds, a function returning the duration, or 0 for no transition. Defaults to 250. - **delay** (Number | function) - Optional - The delay of the transition in milliseconds, or a function returning the delay, or 0 for no delay. - **name** (String) - Optional - The name of the transition (if concurrent transitions on the same elements are needed). ``` -------------------------------- ### beginSlice Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Sets or gets the starting index for the data slice displayed in the table. ```APIDOC ## dataTable.beginSlice([beginSlice]) ### Description Get or set the slice begin index. Used for pagination. ### Method dataTable.beginSlice ### Parameters #### Path Parameters - **[beginSlice]** (Number) ``` -------------------------------- ### Data and Crossfilter Setup for Number Transitions Source: https://github.com/dc-js/dc.js/blob/develop/web-src/transitions/number-transitions.html Sets up the initial data and crossfilter instance with dimensions and group reductions. This is a prerequisite for creating charts that display aggregated numerical data. ```javascript var data = [ { band: "Rush" , member: "Geddy Lee" , number: "5" , othernumber: "3" }, { band: "Rush" , member: "Alex Lifeson" , number: "5" , othernumber: "3" }, { band: "Rush" , member: "Neil Peart" , number: "5" , othernumber: "5" }, { band: "Not Rush" , member: "Somebody Else" , number: "5" , othernumber: "0" } ]; var ndx = crossfilter(data); var dim_band = ndx.dimension(function (d) { return d.band ; }); var dim_member = ndx.dimension(function (d) { return d.member; }); var funcAdd = function(p, v) { p.number += (+v.number ); p.othernumber += (+v.othernumber); return p; }; var funcRemove = function(p, v) { p.number -= (+v.number ); p.othernumber -= (+v.othernumber); return p; }; var funcInitial = function() { return { number : 0 , othernumber : 0 }; }; var grp_band = dim_band .group().reduce(funcAdd, funcRemove, funcInitial); var grp_member = dim_member.group().reduce(funcAdd, funcRemove, funcInitial); var grp_all = ndx.groupAll().reduce(funcAdd, funcRemove, funcInitial); ``` -------------------------------- ### Initialize Charts and Load Data Source: https://github.com/dc-js/dc.js/blob/develop/web-src/examples/heatmap-filtering.html Sets up chart groups, initializes a heatmap and a bar chart, and loads data from a CSV file. Pre-calculates month and year for performance. ```javascript var chartGroup = "chartGroup"; var heatmapChart = new dc.HeatMap("#heatmap", chartGroup); var barChart = new dc.BarChart("#barchart", chartGroup); d3.csv("../ndx.csv").then(function(data) { var dateFormatSpecifier = "%m/%d/%Y"; var dateFormat = d3.timeFormat(dateFormatSpecifier); var dateFormatParser = d3.timeParse(dateFormatSpecifier); data.forEach(function (d) { d.dd = dateFormatParser(d.date); d.month = d3.timeMonth(d.dd).getMonth(); // pre-calculate month for better performance d.year = d3.timeYear(d.dd).getFullYear(); d.close = +d.close; // coerce to number d.open = +d.open; }); var ndx = crossfilter(data); ``` -------------------------------- ### Initialize and Render Pie Chart with Transitions Source: https://github.com/dc-js/dc.js/blob/develop/web-src/transitions/pie-transitions.html Sets up a dc.js pie chart with transition duration, dimensions, and renders it with data from a CSV file. This is the basic setup for a pie chart with interactive filtering capabilities. ```javascript var chart = new dc.PieChart("#test"); var stop, button1, button2, button3; d3.csv("../examples/morley.csv").then(function(experiments) { var ndx = crossfilter(experiments), runDimension = ndx.dimension(function(d) {return "run-"+d.Run;}), speedSumGroup = runDimension.group().reduceSum(function(d) {return d.Speed * d.Run;}); chart .transitionDuration(transitionTest.duration) .width(768) .height(480) .slicesCap(4) .innerRadius(100) .dimension(runDimension) .group(speedSumGroup) .legend(dc.legend()); chart.render(); var expDim = ndx.dimension(function(d) { return d.Expt; }); var run2 = ndx.dimension(function(d) { return "run-"+d.Run;}); window.button1 = transitionTest.oscillate(function() { expDim.filter(2); }, function() { expDim.filter(); }); window.button2 = transitionTest.oscillate(function() { run2.filterFunction(function(d) { return ["run-19", "run-2"].indexOf(d) != -1; }); }, function() { run2.filter(); }); window.button3 = transitionTest.oscillate(function() { run2.filterFunction(function(d) { return ["run-3", "run-5", "run-7", "run-9"].indexOf(d) != -1; }); }, function() { run2.filter(); }); }); ``` -------------------------------- ### Create and Configure a Resizing Pie Chart Source: https://github.com/dc-js/dc.js/blob/develop/web-src/resizing/resizing-pie.html Initializes a pie chart, loads data, configures dimensions and groups, and applies a custom resizing logic. Use this for creating dynamic charts that adapt to screen size. ```javascript var chart = new dc.PieChart("#test"); d3.csv("../examples/morley.csv").then(function(experiments) { var ndx = crossfilter(experiments), runDimension = ndx.dimension(function(d) {return "run-"+d.Run;}), speedSumGroup = runDimension.group().reduceSum(function(d) {return d.Speed * d.Run;}); var adjustX = 20, adjustY = 40; chart .width(window.innerWidth-adjustX) .height(window.innerHeight-adjustY) .slicesCap(4) .dimension(runDimension) .group(speedSumGroup) .legend(dc.legend()); apply_resizing(chart, adjustX, adjustY); chart.on('preRender.resizing preRedraw.resizing', () => { chart.innerRadius(d3.min([chart.width() - adjustX, chart.height() - adjustY]) * 0.2); }); chart.render(); }); ``` -------------------------------- ### Sunburst and Pie Chart Initialization Source: https://github.com/dc-js/dc.js/blob/develop/web-src/examples/sunburst-cat.html Initializes a SunburstChart for file paths and a PieChart for file types. Requires a container element with the specified IDs. ```javascript var fileChart = new dc.SunburstChart("#file\_chart"); var typeChart = new dc.PieChart("#type\_chart"); ``` -------------------------------- ### Install dc.js via CDN Source: https://github.com/dc-js/dc.js/blob/develop/README.md Use these links to include dc.js and its CSS in your project via a Content Delivery Network. ```html https://unpkg.com/dc@4/dist/dc.js https://unpkg.com/dc@4/dist/style/dc.css ``` -------------------------------- ### Initialize CboxMenu and DataTable Source: https://github.com/dc-js/dc.js/blob/develop/web-src/examples/cbox-menu.html Initializes three CboxMenu instances and a DataTable. Ensure the target elements exist in the HTML. ```javascript var cbox1 = new dc.CboxMenu('#cbox1'), cbox2 = new dc.CboxMenu('#cbox2'), cbox3 = new dc.CboxMenu('#cbox3'), datatable = new dc.DataTable('#datatable'); ``` -------------------------------- ### Control Progression: Forward and Reverse Source: https://github.com/dc-js/dc.js/blob/develop/web-src/transitions/bar-progression.html Provides functions to control the bar progression animation. `button1` starts the progression forward, while `button2` starts it in reverse. ```javascript window.button1 = function() { progression .reverse(false) .start(); }; window.button2 = function() { progression .reverse(true) .start(); }; ``` -------------------------------- ### Set or Get Minimum Height - BaseMixin Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Set or get the minimum height attribute of a chart. This setting is most relevant when using the default height function. ```javascript chart.minHeight(200); ``` -------------------------------- ### Set or Get Minimum Width - BaseMixin Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Set or get the minimum width attribute of a chart. This is primarily effective when using the default width function. ```javascript chart.minWidth(200); ``` -------------------------------- ### Crossfilter Setup and Chart Rendering Source: https://github.com/dc-js/dc.js/blob/develop/web-src/examples/replacing-data.html Sets up a crossfilter instance with the initial dataset (data1), defines dimensions and groups, and renders the dc.js charts. This is the initial state before data replacement. ```javascript var ndx = crossfilter(data1), yearDim = ndx.dimension(function(d) {return +d.Year;}), spendDim = ndx.dimension(function(d) {return Math.floor(d.Spent/10);}), nameDim = ndx.dimension(function(d) {return d.Name;}), spendPerYear = yearDim.group().reduceSum(function(d) {return +d.Spent;}), spendPerName = nameDim.group().reduceSum(function(d) {return +d.Spent;}), spendHist = spendDim.group().reduceCount(); function render_plots(){ yearRingChart .width(200).height(200) .dimension(yearDim) .group(spendPerYear) .innerRadius(50); spenderRowChart .width(250).height(200) .dimension(nameDim) .group(spendPerName) .elasticX(true); dc.renderAll(); } render_plots(); ``` -------------------------------- ### Crossfilter Data Preparation and Dimension/Group Setup Source: https://github.com/dc-js/dc.js/blob/develop/web-src/examples/boxplot-render-data.html Initializes a crossfilter dataset and defines a dimension and group for gender, preparing data for box plot visualization. This setup is crucial for enabling interactive filtering and aggregation. ```javascript let ndx = crossfilter(data); // ----------------------------------------------- let bpGenderDim = ndx.dimension(function (d) {return d.gender; }); let bpGenderGroup = bpGenderDim.group().reduce( function (p, v) { // Retrieve the data value, if not Infinity or null add it. let dv = v.age; if (dv != Infinity && dv != null) p.splice(d3.bisectLeft(p, dv), 0, dv); return p; }, function (p, v) { // Retrieve the data value, if not Infinity or null remove it. let dv = v.age; if (dv != Infinity && dv != null) p.splice(d3.bisectLeft(p, dv), 1); return p; }, function () { return []; } ); ``` -------------------------------- ### Setup Range/Focus Charts and Load Data Source: https://github.com/dc-js/dc.js/blob/develop/web-src/examples/focus-dynamic-data.html Initializes two LineCharts, 'focus' and 'zoom', and loads data from 'morley.csv'. It then processes the data, sets up a crossfilter dimension and group, and configures the 'focus' chart to use the 'zoom' chart as its range chart. ```javascript const urlParams = new URLSearchParams(window.location.search), remove = urlParams.get('remove'); var focus = new dc.LineChart("#focus"); var zoom = new dc.LineChart("#range"); d3.csv("morley.csv").then(function(experiments) { experiments.forEach(function(x) { x.Speed = +x.Speed; }); var ndx = crossfilter(experiments), runDimension = ndx.dimension(function(d) {return +d.Run; }), speedSumGroup = runDimension.group().reduceSum(function(d) { return d.Speed * d.Run / 1000; }); focus .width(768) .height(400) .x(d3.scaleLinear().domain([6,20])) .evadeDomainFilter(true) .elasticY(true) .brushOn(false) .yAxisLabel("This is the Y Axis!") .dimension(runDimension) .group(speedSumGroup) .rangeChart(zoom); ``` -------------------------------- ### scatterPlot.canvas Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Set or get the canvas element for the scatter plot. It's generally recommended to use the get method as dc.js handles canvas element generation. This method only provides a valid canvas when useCanvas is set to true. ```APIDOC ## scatterPlot.canvas([canvasElement]) ### Description Set or get canvas element. You should usually only ever use the get method as dc.js will handle canvas element generation. Provides valid canvas only when [useCanvas](#ScatterPlot+useCanvas) is set to `true`. ### Parameters #### Path Parameters - **canvasElement** (CanvasElement | d3.selection) - Optional - The canvas element to set. ### Return Value - **CanvasElement | d3.selection** - The canvas element or d3.selection. ``` -------------------------------- ### compositeChart.shareTitle Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Get or set title sharing for the chart. If set, the [.title()](#BaseMixin+title) value from this chart will be shared with composed children. Note: currently you must call this before `compose` or the child will still get the parent's `title` function! ```APIDOC ## compositeChart.shareTitle([shareTitle]) ### Description Get or set title sharing for the chart. If set, the [.title()](#BaseMixin+title) value from this chart will be shared with composed children. Note: currently you must call this before `compose` or the child will still get the parent's `title` function! ### Method Instance method of CompositeChart ### Parameters #### Path Parameters - **shareTitle** (Boolean) - Optional. Defaults to `true`. ### Returns - Boolean | CompositeChart - The current value of shareTitle or the chart instance for chaining. ``` -------------------------------- ### Basic Bar Chart Configuration with BaseMixin Source: https://context7.com/dc-js/dc.js/llms.txt Configure a basic bar chart using BaseMixin, setting dimension, group, and accessors. Event handlers for 'filtered' and 'renderlet' are demonstrated. ```javascript import crossfilter from 'crossfilter2'; import * as dc from 'dc'; import * as d3 from 'd3'; const data = [ { date: new Date('2021-01-01'), value: 120, category: 'A' }, { date: new Date('2021-01-02'), value: 95, category: 'B' }, { date: new Date('2021-01-03'), value: 200, category: 'A' }, { date: new Date('2021-01-04'), value: 150, category: 'B' }, ]; const ndx = crossfilter(data); const dateDim = ndx.dimension(d => d.date); const dateGroup = dateDim.group().reduceSum(d => d.value); const chart = new dc.BarChart('#my-chart') .dimension(dateDim) // mandatory: crossfilter dimension .group(dateGroup, 'Value') // mandatory: crossfilter group + optional legend name .width(600) .height(300) .keyAccessor(d => d.key) // default: pluck('key') .valueAccessor(d => d.value) // default: pluck('value') .title(d => `${d.key}: ${d.value}`) .label(d => d.value) .renderLabel(true) .ordering(d => d.key) .transitionDuration(500) .on('filtered', (chart, filter) => console.log('filter changed:', filter)) .on('renderlet', chart => console.log('chart rendered')); chart.render(); ``` -------------------------------- ### Setup Ordinal Line Chart Source: https://github.com/dc-js/dc.js/blob/develop/web-src/transitions/ordinal-line-transitions.html Configure a line chart to use an ordinal x-axis with elastic X and Y axes. Ensure brushOn is false for typical line chart behavior. This setup is suitable for data where the x-axis represents discrete categories. ```javascript var chart = new dc.LineChart('#test'); startOrdinal(function(fruitDimension, fruitGroup) { return chart .width(768) .height(380) .x(d3.scaleBand()) .xUnits(dc.units.ordinal) .elasticX(true) .elasticY(true) .brushOn(false) .xAxisLabel('Fruit') .yAxisLabel('Quantity Sold') .dimension(fruitDimension) .group(fruitGroup); }); ``` -------------------------------- ### Initialize and Configure Scatter Plots Source: https://github.com/dc-js/dc.js/blob/develop/web-src/resizing/resizing-scatter-brushing.html Sets up two scatter plots with specific dimensions, scales, labels, and dimensions. Includes configuration for canvas rendering and transition duration. ```javascript var chart1 = new dc.ScatterPlot("#test1"); var chart2 = new dc.ScatterPlot("#test2"); var data = "x,y,z\n" + "1,1,3\n" + "5,2,11\n" + "13,13,13\n"+ "5,3,20\n"+ "12,12,10\n"+ "3,6,8\n"+ "15,2,9\n"+ "8,6,14\n"+ "1,4,9\n"+ "8,8,12\n"; var data = d3.csvParse(data); data.forEach(function (x) { x.x = +x.x; x.y = +x.y; x.z = +x.z; }); var ndx = crossfilter(data), dim1 = ndx.dimension(function (d) { return [" + d.x, " + d.y]; }), dim2 = ndx.dimension(function (d) { return [" + d.y, " + d.z]; }), group1 = dim1.group(), group2 = dim2.group(); var fudge = 40; chart1.width(window.innerWidth/2 - fudge) .height(window.innerHeight - fudge) .useCanvas(useCanvas) .x(d3.scaleLinear().domain([0, 20])) .yAxisLabel("y") .xAxisLabel("x") .clipPadding(10) .dimension(dim1) .excludedOpacity(0.5) .group(group1); chart2.width(window.innerWidth/2 - fudge) .height(window.innerHeight - fudge) .useCanvas(useCanvas) .x(d3.scaleLinear().domain([0, 20])) .yAxisLabel("z") .xAxisLabel("y") .clipPadding(10) .dimension(dim2) .excludedColor('#ddd') .group(group2); if(useCanvas) { chart1.transitionDuration(0); chart2.transitionDuration(0); } ``` -------------------------------- ### BubbleMixin.minRadius Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Set or get the minimum bubble radius. ```APIDOC ## BubbleMixin.minRadius([radius]) ### Description Set or get the minimum bubble radius. ### Parameters #### Path Parameters - **[radius]** (Number) - Optional - The minimum radius for bubbles. ``` -------------------------------- ### Setup and Data Generation for Align Y Axes Source: https://github.com/dc-js/dc.js/blob/develop/web-src/examples/align-axes.html This code sets up helper functions for data distribution and generation, used to create datasets for charting. It defines how data points are scaled and positioned relative to a zero line. ```javascript var posiness = ["heading", "above", "upward", "even", "downward", "below"]; var N = 20; var gen = d3.randomNormal(); function distribute(vals, min, max) { var ext = d3.extent(vals); return vals.map(function(x) { return min + (x - ext[0]) * (max - min) / (ext[1] - ext[0]); }); } function distribution(posi, scale) { var vals = d3.range(N).map(gen); switch (posi) { case 'above': return distribute(vals, scale * 0.2, scale * 1.2); case 'upward': return distribute(vals, -scale * 0.1, scale * 0.9); case 'even': return distribute(vals, -scale * 0.5, scale * 0.5); case 'downward': return distribute(vals, -scale * 0.9, scale * 0.1); case 'below': return distribute(vals, -scale * 1.2, -0.2); default: throw 'no'; } } function dataset(lposi, rposi) { var ldist = distribution(lposi, 10), rdist = distribution(rposi, 100); return ldist.map(function(v, i) { return {key: i, lvalue: v, rvalue: rdist[i]}; }); } ``` -------------------------------- ### BubbleMixin.r Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Set or get the bubble radius scale. ```APIDOC ## BubbleMixin.r([bubbleRadiusScale]) ### Description Set or get the bubble radius scale. ### Parameters #### Path Parameters - **[bubbleRadiusScale]** (d3.scale) - Optional - The d3 scale for bubble radius. ``` -------------------------------- ### Crossfilter Initialization and Dimension/Group Setup Source: https://github.com/dc-js/dc.js/blob/develop/web-src/examples/horizon-chart.html Initializes a crossfilter instance with the transformed data and sets up dimensions and groups for various chart interactions. Includes dimensions for experiment/run, run filter, experiment, quantized speed, and run. ```javascript const cf = crossfilter(experiments2); const exptRunDim = cf.dimension(d => [d.Expt, d.Run]); const exptRunGroup = exptRunDim.group().reduceSum(d => d.Speed); const seriesRunDimension = cf.dimension(d => [d.Expt, d.Run]); const seriesRunGroup = seriesRunDimension.group().reduceSum(d => d.Speed); const runFilterDim = cf.dimension(d => d.Run); horizonChart .group(sort_multikey_group(exptRunGroup)) .colors(n => [d3.schemeBlues, d3.schemeOranges, d3.schemeGreens, d3.schemeReds, d3.schemePurples][n-1][6]) // levels * 2 .seriesAccessor(d => d.key[0]) .valueAccessor(d => d.value - 500); seriesChart .width(760) .height(250) .transitionDuration(0) .margins({left: 0, right: 0, top: 0, bottom: 0}) .chart(c => new dc.LineChart(c).curve(d3.curveCardinal).defined(d => d.data.value)) .x(d3.scaleLinear().domain([1,20])) .y(d3.scaleLinear().domain(d3.extent(seriesRunGroup.all(), d => d.value-500))) .brushOn(true) .clipPadding(10) .dimension(runFilterDim) .group(seriesRunGroup) .seriesAccessor(d => d.key[0]) .keyAccessor(d => d.key[1]) .valueAccessor(d => d.value - 500) .legend(dc.legend().x(350).y(180).itemHeight(13).gap(5).horizontal(1).legendWidth(140).itemWidth(70)); const exptDim = cf.dimension(d => d.Expt), exptGroup = exptDim.group(); exptPie .width(250) .height(250) .colors(d3.scaleOrdinal().domain([1,6]).range(d3.schemeCategory10)) .dimension(exptDim) .group(exptGroup); const speeds = ['low', 'medium low', 'medium', 'medium high', 'high']; const quantizeSpeed = d3.scaleQuantize() .domain(d3.extent(experiments2, d => d.Speed)) .range(speeds); const quantizeSpeedDim = cf.dimension(d => quantizeSpeed(d.Speed)), quantizeSpeedGroup = quantizeSpeedDim.group(); speedPie .width(250) .height(250) .ordering(d => speeds.indexOf(d.key)) .colors(d3.scaleOrdinal().domain(speeds).range(d3.schemeRdYlGn[speeds.length].slice().reverse())) // range(d3.range(0, 1, 1/speeds.length).map(d3.interpolateTurbo))) .minAngleForLabel(0) .dimension(quantizeSpeedDim) .group(quantizeSpeedGroup); speedPie.on('pretransition', c => { c.select('.pie-label._2').style('fill', '#422518'); }); const runDim = cf.dimension(d => Math.floor(d.Run)), runGroup = runDim.group(); runPie .width(250) .height(250) .colors(d3.scaleOrdinal().domain(d3.range(1,21)).range(d3.range(0,29).map(d => { const x = (d+10)*255/29; return `rgb(${x},${x},${x})`; }))) .ordering(d => d.key) .minAngleForLabel(0) .dimension(runDim) .group(runGroup); ``` -------------------------------- ### ColorMixin.colorCalculator Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Gets or sets the color calculator function. ```APIDOC ## colorMixin.colorCalculator([colorCalculator]) ### Description Gets or sets the color calculator function. This function is responsible for calculating the final color for a given data point. ### Method instance method of `ColorMixin` ### Parameters #### Path Parameters - **[colorCalculator]** (function) - An optional function that calculates the color for a data point. ### Returns - function | [ColorMixin](#ColorMixin) - Returns the current color calculator function or the ColorMixin instance for chaining. ``` -------------------------------- ### Build and Test dc.js Source: https://github.com/dc-js/dc.js/blob/develop/README.md Build the dc.js library and run its test suite using the grunt task runner. ```bash $ grunt test ``` -------------------------------- ### ColorMixin.colorDomain Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Gets or sets the domain of the color scale. ```APIDOC ## colorMixin.colorDomain([domain]) ### Description Gets or sets the domain of the color scale. The domain is the set of values that the color scale will map data to. ### Method instance method of `ColorMixin` ### Parameters #### Path Parameters - **[domain]** (Array<String>) - An optional array representing the domain of the color scale. ### Returns - Array.<String> | [ColorMixin](#ColorMixin) - Returns the current domain of the color scale or the ColorMixin instance for chaining. ``` -------------------------------- ### Initialize Data and Crossfilter Source: https://github.com/dc-js/dc.js/blob/develop/web-src/examples/text-filter-widget.html Sets up the initial dataset and creates a crossfilter instance. The dimension is defined to combine first and last names for filtering. ```javascript var data = [ {'first_name': 'John', 'last_name': 'Coltrane'}, {'first_name': 'Miles', 'last_name': 'Davis'}, {'first_name': 'Ornette', 'last_name': 'Coleman'}, {'first_name': 'Louis', 'last_name': 'Armstrong'}, {'first_name': 'Fela', 'last_name': 'Kuti'}, {'first_name': 'Charlie', 'last_name': 'Parker'}, {'first_name': 'Wayne', 'last_name': 'Shorter'}, {'first_name': 'Thelonious', 'last_name': 'Monk'}, {'first_name': 'Herbie', 'last_name': 'Hancock'}, {'first_name': 'Max', 'last_name': 'Roach'} ]; var ndx = crossfilter(data), dimension = ndx.dimension(function (d) { return d.last_name + ' ' + d.first_name; }); ``` -------------------------------- ### ColorMixin.colorAccessor Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Gets or sets the color accessor function. ```APIDOC ## colorMixin.colorAccessor([colorAccessor]) ### Description Gets or sets the color accessor function. The color accessor function is used to determine the value that will be used to map to a color. ### Method instance method of `ColorMixin` ### Parameters #### Path Parameters - **[colorAccessor]** (function) - An optional function that returns the value to be used for color mapping. ### Returns - function | [ColorMixin](#ColorMixin) - Returns the current color accessor function or the ColorMixin instance for chaining. ``` -------------------------------- ### Example: Pluck Property 'x' Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Demonstrates creating a function to pluck the 'x' property from an object. ```javascript var xPluck = pluck('x'); var objA = {x: 1}; xPluck(objA) // 1 ``` -------------------------------- ### ColorMixin.colors Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Gets or sets the color scale for the chart. ```APIDOC ## colorMixin.colors([colorScale]) ### Description Gets or sets the color scale for the chart. If a `colorScale` is provided, it will be set as the chart's color scale. If no argument is provided, it returns the current color scale. ### Method instance method of `ColorMixin` ### Parameters #### Path Parameters - **[colorScale]** (d3.scale) - An optional D3 color scale to set for the chart. ### Returns - d3.scale | [ColorMixin](#ColorMixin) - Returns the current D3 color scale or the ColorMixin instance for chaining. ``` -------------------------------- ### Data Loading and Crossfilter Setup Source: https://github.com/dc-js/dc.js/blob/develop/web-src/examples/sunburst-cat.html Loads data from a TSV file and sets up a crossfilter instance. This is a prerequisite for creating dimensions and groups. ```javascript d3.tsv("cat.tsv").then(function (cats) { var ndx = crossfilter(cats); // ... chart configurations ... dc.renderAll(); }); ``` -------------------------------- ### PieChart.radius Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Gets or sets the radius of the pie chart. ```APIDOC ## pieChart.radius([radius]) ⇒ Number | PieChart ### Description Get or set the radius of the pie chart. ### Parameters #### Path Parameters - **[radius]** (Number) ### Method GET or SET ### Endpoint /pieChart/radius ``` -------------------------------- ### Create Bar and Pie Charts with Crossfilter Source: https://github.com/dc-js/dc.js/blob/develop/web-src/examples/adjustable-threshold.html Initializes data, creates bar and pie chart objects, and sets up crossfilter dimensions and groups for charting. ```javascript var data = [ { "book": "A", "scores": 45 }, { "book": "B", "scores": 34 }, { "book": "C", "scores": 54 }, { "book": "D", "scores": 27 }, { "book": "E", "scores": 70 }, { "book": "F", "scores": 25 }, { "book": "G", "scores": 92 }, { "book": "H", "scores": 22 }, { "book": "I", "scores": 40 }, { "book": "J", "scores": 10 }, { "book": "K", "scores": 40 } ]; //## Create Chart Objects var scoreChart = new dc.BarChart("#dc-score-barchart") .xAxisLabel('book_id') .yAxisLabel('score'); var goodYesNoPieChart = new dc.PieChart('#dc-coreAcc-piechart'); //### Create Crossfilter Dimensions and Groups var ndx = crossfilter(data); var all = ndx.groupAll(); var bookDimension = ndx.dimension(function (d) {return d.book;}), bookscoresGroup = bookDimension.group().reduceSum(function(d) {return d.scores;}); //## score bar chart scoreChart.width(320) .height(320) .dimension(bookDimension) .group(bookscoresGroup) .elasticY(true) .x(d3.scaleBand()) .xUnits(dc.units.ordinal) .colors(["orange"]) .yAxis().ticks(5); ``` -------------------------------- ### legend.y([y]) Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Set or get the y coordinate for the legend widget. ```APIDOC ## legend.y([y]) ### Description Set or get y coordinate for legend widget. ### Method GET/SET ### Parameters #### Path Parameters - **y** (Number) - Optional - The y coordinate for the legend widget. ### Response #### Success Response (200) - **y** (Number) - The current y coordinate of the legend widget. - **Legend** - Returns the Legend object for chaining. ``` -------------------------------- ### dataGrid.order Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Get or set sort the order function. ```APIDOC ## dataGrid.order([order]) ### Description Get or set sort the order function. ### Parameters #### Path Parameters - **order** (function) - Optional - The function to determine the sort order. Defaults to `d3.ascending`. ### See Also - [d3.ascending](https://github.com/d3/d3-array/blob/master/README.md#ascending) - [d3.descending](https://github.com/d3/d3-array/blob/master/README.md#descending) ### Request Example ```js chart.order(d3.descending); ``` ``` -------------------------------- ### Data Generation and Chart Initialization Source: https://github.com/dc-js/dc.js/blob/develop/web-src/examples/focus-dynamic-interval.html Generates a large dataset with time-series values and initializes the main focus chart and the range chart. ```javascript const data = []; const items = 500000; // way way too much const start = Date.now(); for (i = 0; i < items; i++) { const t = start + i * 50; const d = new Date(t); data.push({ value: 10 * Math.sin(2 * Math.PI * t / (60 * 60 * 1000)), date: d }); } const chart = new MyLineChart('#chart'); const rangeChart = new dc.LineChart('#range-chart'); const fullDomain = [data[0].date, data.slice(-1)[0].date]; const dimension = crossfilter(data).dimension(d => d.date); ``` -------------------------------- ### Instantiate LineChart Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Create a LineChart instance. Specify the parent DOM element or composite chart and an optional chart group for managing interactions. ```javascript var chart1 = new LineChart('#chart-container1'); var chart2 = new LineChart('#chart-container2', 'chartGroupA'); var chart3 = new LineChart(compositeChart); ``` -------------------------------- ### boxPlot.showOutliers Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Get or set whether outliers will be rendered. ```APIDOC ## boxPlot.showOutliers([show]) ### Description Get or set whether outliers will be rendered. ### Parameters #### Path Parameters - **show** (Boolean) - Optional - Whether to render outliers. Defaults to true. ### Request Example ```js // Disable rendering of outliers chart.showOutliers(false); ``` ### Response #### Success Response (200) - **Boolean** | **BoxPlot** - Returns the current outlier rendering setting or the BoxPlot instance for chaining. ``` -------------------------------- ### Configure and Render Area Chart with Transitions Source: https://github.com/dc-js/dc.js/blob/develop/web-src/transitions/area-transitions.html Sets up a LineChart with area rendering enabled and transitions applied. It configures dimensions, groups, and stacks for visualizing data over time. ```javascript var chart = new dc.LineChart("#test"); d3.csv("../examples/morley.csv").then(function(experiments) { experiments.forEach(function(x) { x.Speed = +x.Speed; }); var ndx = crossfilter(experiments), runDimension = ndx.dimension(function(d) {return +d.Run; }), speedSumGroup = runDimension.group().reduce(function(p, v) { p[v.Expt] = (p[v.Expt] || 0) + v.Speed; return p; }, function(p, v) { p[v.Expt] = (p[v.Expt] || 0) - v.Speed; return p; }, function() { return {}; }); function sel_stack(i) { return function(d) { return d.value[i]; }; } var doDots = transitionTest.querystring.dots !== "0", doArea = transitionTest.querystring.area !== "0"; chart .transitionDuration(transitionTest.duration) .width(768) .height(480) .x(d3.scaleLinear().domain([1, 20])) .margins({left: 50, top: 10, right: 10, bottom: 20}) .renderArea(doArea) .brushOn(false) .renderDataPoints(doDots) .yAxisLabel("This is the Y Axis!") .dimension(runDimension); function all_stacks() { chart.group(speedSumGroup, "1", sel_stack('1')); for (var i = 2; i < 6; ++i) chart.stack(speedSumGroup, '' + i, sel_stack(i)); } all_stacks(); chart.render(); var reset = function() { chart.x().domain([1, 20]); } window.button1 = transitionTest.oscillate(function() { chart.x().domain([1, 10]); }, reset); window.button2 = transitionTest.oscillate(function() { chart.x().domain([16, 20]); }, reset); window.button3 = transitionTest.oscillate(function() { chart.x().domain([6.5, 13.5]); }, reset); window.button4 = transitionTest.oscillate(function() { chart.group(speedSumGroup, '2', sel_stack('2')) .stack(speedSumGroup, '4', sel_stack('4')); }, all_stacks); }); ``` -------------------------------- ### boxPlot.dataOpacity Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Get or set the opacity when rendering data. ```APIDOC ## boxPlot.dataOpacity([opacity]) ### Description Get or set the opacity when rendering data. ### Parameters #### Path Parameters - **opacity** (Number) - Optional - The opacity value. Defaults to 0.3. ### Request Example ```js // If individual data points are rendered increase the opacity. chart.dataOpacity(0.7); ``` ### Response #### Success Response (200) - **Number** | **BoxPlot** - Returns the current data opacity or the BoxPlot instance for chaining. ``` -------------------------------- ### BubbleMixin.maxBubbleRelativeSize Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Set or get the maximum relative size of a bubble. ```APIDOC ## BubbleMixin.maxBubbleRelativeSize([relativeSize]) ### Description Set or get the maximum relative size of a bubble. ### Parameters #### Path Parameters - **[relativeSize]** (Number) - Optional - The maximum relative size for bubbles. ``` -------------------------------- ### External Data Loading Example Source: https://github.com/dc-js/dc.js/wiki/Optimization-and-Performance-Tuning An external gist demonstrating an approach to parsing data as it's transferred, potentially improving load times for large datasets. ```html https://gist.github.com/jrideout/7111894/raw/ed0eeb28c87b572e2b441dfc371036f36c0a3745/index.html ``` -------------------------------- ### BubbleMixin.minRadiusWithLabel Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Set or get the minimum bubble radius with a label. ```APIDOC ## BubbleMixin.minRadiusWithLabel([radius]) ### Description Set or get the minimum bubble radius with a label. ### Parameters #### Path Parameters - **[radius]** (Number) - Optional - The minimum radius for bubbles with a label. ``` -------------------------------- ### Initialize Range Bar Chart - JavaScript Source: https://github.com/dc-js/dc.js/blob/develop/web-src/examples/focus-ordinal-bar.html Sets up the range selection bar chart, which works in conjunction with the focus chart. It shares the same linear domain and integer units but has brush enabled for range selection. ```javascript range = new dc.BarChart('#range'); range.filterHandler(function() {}); // disable built-in filtering range .margins({left: 74, top: 0, right: 20, bottom: 2}) .width(1000).height(20) .x(d3.scaleLinear().domain(linear_domain)) .xUnits(dc.units.integers) .keyAccessor(kv => group.ord2int(kv.key)) .elasticY(true) .brushOn(true) .dimension(dimension) .group(group) .transitionDuration(0); focus.rangeChart(range) ``` -------------------------------- ### BubbleMixin.radiusValueAccessor Source: https://github.com/dc-js/dc.js/blob/develop/docs/api-latest.md Set or get the radius value accessor function. ```APIDOC ## BubbleMixin.radiusValueAccessor([radiusValueAccessor]) ### Description Set or get the radius value accessor function. ### Parameters #### Path Parameters - **[radiusValueAccessor]** (function) - Optional - The function to access the radius value. ```