Skip to content
Irene Ros edited this page May 27, 2013 · 22 revisions

API Reference

Chart

Creation:

Extension

Instantiation:

Instance properties:

Instance methods:

Layer

Creation

Instance Methods:


Chart

d3.chart(name, options)

Description:

Used to define a new chart type.

Parameters:

  • name - the name of the chart one wishes to create. This is the generic 'type' of chart you're creating, for example 'barchart' rather than an instance of a chart that you're initializing.
  • options - the methods that will be available to the chart instance. See creating for more information on defining a chart.

Uses:

Example chart creation:

d3.chart('MyChartType', {
  initialize: function() {
  }
  // any additional instance methods go here.
});

d3.chart(chartType).extend(name, protoProps, staticProps)

Description:

Allows the extension of an existing d3.chart of chartType type.

Parameters:

  • name - The new chart type name of the extended chart. For example, when extending a BarChart, one may want to add hoverable behavior to the bars. An appropriate name would then be: HoverableBarChart.
  • protoProps - A set of properties/methods that will be added to each instance of the chart.
  • staticProps - A set of properties/methods that will be added to the constructor of the chart, but not each instance.

Uses:

Example:

// define a new chart type:
d3.chart("MyChart", {});

// extend it:
d3.chart("MyChart").extend("MyExtendedChart", {
 hoverable: function() {}
});

// create an extended chart type instance:
var chart = d3.select("#vis")
  .append("svg")
  .chart("MyExtendedChart")
  .hoverable(); // method is now available.

<selection>.chart(name)

Description:

Used to create a chart instance on a selection or retrieve the chart reference within a layer.

Parameters:

  • name - the name of the chart one wishes to use. Optional.

Uses:

There are two types of uses for the .chart method when called on a selection:

  1. To initialize a chart from a selection. For example:
var chart = d3.select("div#vis")
  .append("svg")
  .attr("width", 200)
  .attr("height", 200)
  .chart("BarChart"); // assuming we've defined a BarChart chart type.
  1. To retrieve the chart associated with a layer from within the layer methods:
// from within a chart definition:
chart.layer({
  dataBind: function(data) {
    var chartInstance = this.chart();
  }
});

Note you can only retrieve the chart from the layer, not from any selection that could possibly live within a chart's DOM tree.


<instance>.base

Description:

The highest level selection from which a chart was created.

Uses:

For example:

var selection = d3.select("#vis")
  .append("svg");

var chart = selection.chart("MyChart");
// Note: (chart.base == selection) is true.

<instance>.trigger(name)

Description:

Used to trigger an event on a chart. At least the name of the event is required. Any arguments passed after the name parameter will be passed to the callback.

Parameters:

  • name - Name of event to trigger.

Uses:

For example:

var chart = d3.select("#vis")
	.append("svg")
	.chart("MyChart");

chart.on("AnEvent", function() {
  // react to said event
});	
chart.on("SomeEvent", function(arg1, arg2) {
  //react to said event
});

chart.trigger("AnEvent");
chart.trigger("SomeEvent", 12, 14);

<instance>.on(name, callback, context)

Description:

Binds a callback to the chart instance for a specific event name. Optionally can provide a context in which the callback be executed. By default, the context will be that of the chart instance.

Parameters:

  • name - Name of the event to bind to
  • callback - The callback to execute when that event triggers
  • context - The context in which the callback will be executed. Optional.

Uses:

Example:

var chart = d3.select("#vis")
	.append("svg")
	.chart("MyChart");
	
chart.on("SomeEvent", function(arg1, arg2) {
  //react to said event
});

chart.trigger("SomeEvent", 12, 14);

<instance>.once(name, callback, context)

Description:

Binds a callback to the chart instance for a specific event name. This callback will only execute once. Optionally can provide a context in which the callback be executed. By default, the context will be that of the chart instance.

Parameters:

  • name - Name of the event to bind to
  • callback - The callback to execute when that event triggers
  • context - The context in which the callback will be executed. Optional.

Uses:

Example:

var chart = d3.select("#vis")
	.append("svg")
	.chart("MyChart");
	
chart.once("SomeEvent", function(arg1, arg2) {
  //react to said event
  console.log(arg1, arg2);
});

chart.trigger("SomeEvent", 12, 14); // => 12,14
chart.trigger("SomeEvent", 20, 34); // nothing happens.

<instance>.off(name, callback, context)

Description:

Used to unbind events previously bound to the chart.

Parameters:

  • name - Name of event to unbind. Optional.
  • callback - The specific callback to unbind. Optional.
  • context - The context for which to unbind.

Uses:

  • Calling .off without any parameters will result in all events being unbound:
var chart = d3.select("#vis")
	.append("svg")
	.chart("MyChart");

chart.on("AnEvent", function() {
  // react to said event
});	
chart.on("SomeEvent", function(arg1, arg2) {
  //react to said event
});

chart.off(); //unbinds both AnEvent and SomeEvent
  • Calling .off with a name parameter will result in all events bound to that event name being unbound:
var chart = d3.select("#vis")
	.append("svg")
	.chart("MyChart");

chart.on("AnEvent", function() {
  // react to said event
});	
chart.on("SomeEvent", function(arg1, arg2) {
  //react to said event
});

chart.off("AnEvent"); //unbinds AnEvent, but not SomeEvent
  • Calling .off with a callback will unbind all events for which that callback is set. A name can be provided but isn't required.
var chart = d3.select("#vis")
	.append("svg")
	.chart("MyChart");

var callback = function() {
  // react to event
};
chart.on("AnEvent", callback);	
chart.on("SomeEvent", callback);

chart.off("SomeEvent", callback); // unbines only the SomeEvent callback
chart.off(undefined, callback);   //unbinds both AnEvent and SomeEvent
  • Calling .off with a context will unbind all events for which that the callback will execute with said context. The name and callback can be provided by are not required.
var chart = d3.select("#vis")
	.append("svg")
	.chart("MyChart");

var context = {};
var callback = function() {
  // react to event
};
chart.on("AnEvent", callback, context);	
chart.on("SomeEvent", callback, context);

chart.off(undefined, undefined, context); //unbinds both AnEvent and SomeEvent
chart.off("AnEvent", undefined, context);   //unbinds AnEvent
chart.off(undefined, callback, context);   //unbinds both AnEvent and SomeEvent

<instance>.layer(name, selection, options)

Description:

Defines a new layer on a chart or returns a reference to the selection corresponding to a layer by a specific name.

Parameters:

  • name - Name of layer. Optional.
  • selection - The d3 selection that will be made into a layer.
  • options - The specific options available during layer creation:
    • events - An object specifying lifecycle events. Keys are the event names and the values are the callbacks.
    • dataBind - The function that sets up the selection and binds the data using the d3 .data() function. Must return that binding. Takes one argument which is the data that draw was called with, transformed if the transform method was defined. The context of the dataBind method is the selection of the layer.
    • insert - The function that gets called once the d3 .enter() method is executed. Note that happens internally. The context of the insert function is the entered selection.

Uses:

  1. To create a new layer:
d3.chart("MyChart", {
  initialize: function() {

    // define a selection that will be used
    // to display our rects
    var barArea = this.base.append("g")
      .classed("bars", true);

    // create a new layer on the chart    
    this.layer("bars", barArea, {
      events: {

        // when new data enters, set its x attribute
        // according to the value of the datum.
        "enter" : function() {
          return this.attr("x", function(d) { 
            return d.value; 
          });
        }
      },
      dataBind: function(data) {
        // return a selection & data binding
        return this.selectAll("rect")
          .data(data);
      },
      insert: function() {
        // once the selection has been entered, append
        // the appropriate elements. Note we are not actually
        // setting the data-driven attributes here - those happen
        // on the enter event.
        return this.append("rect");
      }
    });
  }
});
  1. To return a layer:
var chart = d3.select("#vis")
  .append("svg")
  .chart("MyChart");
  
var barLayer = chart.layer("bars");

This is most useful when extending the chart to include custom or additional functionality.


<instance>.draw(data)

Descripion:

Causes the chart to draw all its layers as well as any layers defined in mixins. Note that this is the only way to pass data to the chart - through the draw method.

Parameters:

  • data - The data that should be drawn. Note that if a transform method was defined for the data, it will be first passed through that transform before it is handed off to the layers. The dataBind methods of each layer will recieve the transformed data.

Uses:

Example:

var chart = d3.select("#vis")
	.append("svg")
	.chart("MyChart");
	
var data = [1,2,3,4];
chart.draw(data);

<instance>.transform(data)

Description:

Transforms the data into a format that is expected by the layers. By default the transform method just passes the original data thrgouh. Define the transform method as a part of the chart definition.

Note you will most likely never call this method directly, but rather define it during chart definition. Nonetheless it is a method that is availabe on the instance.

Parameters:

  • data - The data to transform.

Uses:

d3.chart("MyChart", {
  transform: function(data) {
    return data.values;
  }
});

var chart = d3.select("#vis")
  .append("svg")
  .chart("MyChart");
  
chart.transform({ values : [1,2,3] }); // results in [1,2,3].

<instance>.mixin(chartType, selection)

Description:

Allows adding an instance of a chart onto an instance of another. See an example of the [whacky chord/bar chart](TODO://linktomike's whacky bar/chord chart.) The mixin approach affords two things:

  • It allows tying together of charts that are driven by the same data
  • It superimposes charts on top of each other - sharing the same base but separating their functionality. Note it is up to you to pass on a selection that is derived off of the base of the chart being mixed into. See example below.

Parameters:

  • chartType - The name of the chart type that will be initilized.
  • selection - The d3 selection that will be used to create the new chart type.

Uses:

For example if you have pie charts and barcharts that are each drawn for a value, if you want to superimpose them on top of each other.

*Note that both charts must work with the same data. When callilng the draw method of the chart into which a secondary chart is mixed in, the draw methods of the mixed in chart will be called with the same data passed to the first chart's draw.

For example:

// Define your chart types
d3.chart("MyChart", {});
d3.chart("MyOtherChart", {});

// Create the first chart
var chart1 = d3.select("#vis")
  .append("svg")
  .chart("MyChart");
  
// Mix into the first chart a new instance
// of the other chart. Note we are using the original `base`
// of the first chart and adding a region to it that is specific
// to the new chart. This is not required - it can be a new selection.
chart1.mixin("MyOtherChart", chart1.base.append("g"));

Layer

Layers can exist without a chart, but are recommended as key construct of chart definition.

<selection>.layer(options)

Description:

Creates a new from a d3.selection.

Parameters:

  • options - The specific options available during layer creation. See <chart_instance>.layer for a description of the options parameter.

Uses:

Example:

// define a layer
var layer = d3.select("#vis")
  .append("svg")
  .layer({
    dataBind: function(data){
      return this.selectAll("rect")
        .data(data);
    },
    insert: function() {
      return this.append("rect");
    }
  });

// render the layer  
layer.draw([1,2,3]);

<instance>.draw(data)

Description:

Allows directly drawing a layer. Note that if your layer is defined as part of a chart, when you call the chart instance's draw method, it will automatically call the draw method of all its layers.

Parameters:

  • data - The data based on which to draw the layer.

Uses:

For example:

// define a layer
var layer = d3.select("#vis")
  .append("svg")
  .layer({
    dataBind: function(data){
      return this.selectAll("rect")
        .data(data);
    },
    insert: function() {
      return this.append("rect");
    }
  });

// render the layer  
layer.draw([1,2,3]);

<selection>.chart()

Description:

Returns the chart with which the layer is associated. This is most useful inside of the dataBind, insert and any lifecycle event callback methods where the default context is set to the layer selection (on which you can call this chart method.) See example for more details.

Uses:

For example:

d3.chart("MyChart", {
  initialize: function() {
	// example of needing to define values on the chart
	// instance that then may need to be accessible 
    this.prop = 12;
    
    // create a new layer called "test" that will live in a "g"
    // element right off of the base of this chart.
    this.layer("test", this.base.append("g"), {
      dataBind: function(data) {
      
        // retrieve the chart instance so that you can
        // then get the prop value we defined above.
        var chart = this.chart();
        return this.selectAll("rect")
          .data(data * chart.prop); // presumably do something more meaningful.
      },
      insert:function() {
        return this.append("rect");
      }
    });
  }
});

<instance>.on(eventName, handler, options)

Description:

Allows binding of callbacks to lifecycle events. Note that you can only bind to the lifecycle events of a layer, NOT any random event. The intent is to use the high level chart as the event bus, but to allow binding more directly to lifecycle events on the layers for the purpose of extension.

*Note you can also bind to events when defining a layer by using the events property in the options parameter.

Parameters:

  • eventName - The name of the lifecycle event to bind to. Allowed events are: update, enter, merge, exit, update:transition,enter:transition, merge:transition and exit:transition.
  • handler - The callback to execute when the event type is trigered. Note that you can't directly overwrite the context of this handler. It's important that the context be set by the binding because it is going to be the selection upon which you would operate.
  • options - An object containing optional arguments. Optional arguments include:
    • chart - The chart that should be the returned when a callback references this.chart(). This is particularly useful when building a single chart that is a combination of several through mixins.

Uses:

Example:

d3.chart("MyChart", {
  initialize: function() {
  
    // define a new test layer
    var layer = this.layer("layer1", this.base.append("g"), {
      dataBind: function(data) {
        return this.selectAll("rect")
          .data(data);
      },
      insert: function() {
        return this.append("rect");
      }
    });
    
    // bind to the layer's enter event the setting of the actual
    // position related attribute.
    layer.on("enter", function() {
      return this.attr("x", function(d) {
        return d.x;
      });
    });
  }
});

<instance>.off(eventName, handler)

Description:

Allows for unbinding from a lifecycle event.

Parameters:

  • eventName - The event from which to unbind.
  • handler - The specific handler to unbind. Optional.

Uses:

For example:

d3.chart("MyChart", {
  initialize: function() {
    // define a new test layer
    var layer = this.layer("layer1", this.base.append("g"), {
      dataBind: function(data) {
        return this.selectAll("rect")
          .data(data);
      },
      insert: function() {
        return this.append("rect");
      }
    });
    
    // by default, make the layer elements
    // hoverable
    layer.on("enter", this.hoverable);
  },
  
  // make an entered selection hoverable by just
  // appending the 'selected' classname to it when
  // it is hovered.
  hoverable: function() {
    var self = this;
    this.on("mouseover", function() {
      self.classed("selected", true);
    })
    .off("mouseout", function() {
       self.classed("selected", false);
    });
    
  },
  
  // removes the hoverable behavior by turning off the specific
  // enter callback that enabled it.
  unhoverify: function() {
    this.layer("layer1").off("enter", this.hoveralble)
  }
});

<instance>.dataBind(data)

Description:

The layer functionality that selects the appropriate elements onto which data will be bound, and binds the data. It returns that data-bound selection.

Note you will never need to call this method directly. It is invoked as part of the draw call.

Parameters:

  • data - The data being bound.

Uses:

See layer creation to see how dataBind is defined. Because it is not to be called directly, no example is provided.


<instance>.insert()

Description:

The layer functionality that will be called on each entered element from the bound data via dataBind.

Note you will never need to call this method directly. It is invoked as part of the draw call.

Uses:

See layer creation to see how insert is defined. Because it is not to be called directly, no example is provided.