d3 xAxis with ordinal scale and a click event?

I will build a chart with an x-axis (ordinal scale). Every label at the axis have a click event. The data for the x-Axis Labels are stored in JSON objects (xAxisData.Label) - my xscale.domain. But when I click on a label, I need the ID from the json object (but my data domain are only the Labels). So how can I store the ID additional to the Label ? thx....!!

xAxisData: {
              ID: 1,
              TimeStamp: 01.01.2014 00::00,
              Label: "00:15",

xAxisLabels = d3.set(xAxisData.map(function (d) { return d.Label; })).values(); 

xScale = d3.scale.ordinal()
            .rangeBands([0, chartWidth], 0.1)


You can use the objects themselves as input to the domain:

xScale = d3.scale.ordinal()
        .rangeBands([0, chartWidth], 0.1)

Then, to get the Label as label, use the .tickFormat() function of your axis:

xAxis = d3.svg.axis().scale(xScale)
          .tickFormat(function(d) { return d.Label; });

Now the data bound to the ticks includes everything and you can use d.ID in your event handler.


This doesn't quite work as expected because D3 coerces the domain values into strings and maps them to the scale indices. This doesn't work in this case, as objects are always coerced to the same value. A quick fix is to specify the stringification yourself (i.e. convert to JSON) and take care of the necessary conversions behind the scenes:

xScale = d3.scale.ordinal()
            .rangeBands([0, w], 0.1); // 1%

xAxis = d3.svg.axis()
         .tickFormat(function (d) {
             return JSON.parse(d).label;

Complete example here.

Need Your Help

Does Netbeans support vs-doc syntax for providing Javascript intellisense?

javascript visual-studio ide netbeans intellisense

I've been documenting my Javascript with v-doc comments, as this works really nicely with Visual Studio.

Python def replace

python python-2.7 python-3.x

What would the body be if I was to make a function that is designed to modify lst so that its element at pos is replaced with item. Without built-in functions