Map custom value field to x value when using a stacked layout

I successfully mapped y values, but I'm having trouble mapping an x value to an arbitrary field on my values when creating a stacked bar graph using the stack layout. I'm not really familiar with Javascript and d3; so I'm probably missing something basic here.

A value in my array of data looks like { "xInit": 0, "yInit": 91 }. I want to map xInit to x in the graph and yInit to y.

This works (suggested by Bryan Clark):

var st = d3.layout
           .stack()
           .values(function (d) { return d.values; })
           .y(function (v, i) { return v.yInit; })
           .out(function (d, y0, y) { d.x = d.xInit; d.y0 = y0; d.y = y; });

This works, the x coords are taken from value.xInit

And this doesn't:

var st = d3.layout.stack()
           .values(function (d) { return d.values; })
           .y(function (v, i) { return v.yInit; })
           .x(function (v, i) { return v.xInit; });

Fail! value.x returns NaN

It gives the following warnings:

Unexpected value translate(NaN,0) parsing transform attribute.
Unexpected value NaN parsing x attribute.

Am I using stack.x([accessor]) incorrectly here? How should I use it then?

Details

A complete example showing my problem is available as a block based on this gist. I would like to create a stacked bar graph based on the following data:

initialData = [ {
          "name": "apples",
          "values": [{ "xInit": 0, "yInit": 91 }, { "xInit": 1, "yInit": 290 }, { "xInit": 2, "yInit": 120 }]
      },{
          "name": "oranges",
          "values": [{ "xInit": 0, "yInit": 9 }, { "xInit": 1, "yInit": 49 }, { "xInit": 2, "yInit": 37 }]
      }];

Answers:

Answer

I'm not entirely clear what you're trying to do here so this isn't a full solution but I'll help you get going.

You can manipulate the outgoing data with the out() function to get the x coordinate you're looking for and thus make your graph happen.

var st = d3.layout.stack()
        .values(function(d) { return d.values; })
        .out(function(d, y0, y) {d.x = d.xInit; d.y0 = y0; d.y = y; })
        .y(function (v, i) { return v.yInit; });

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.