Accepted answer

In the example you linked, the original data is grouped by band type. Your data is grouped by set - that is, in the original each color band is grouped in the data array. In your data, each stack of bands is a group of objects in the data array.

If you want to reuse the original code, we need to translate the data (90 degrees) like so:

var initialData = [{x:"abc",  y1:"3",  y2:"4",  y3:"10"},
                   {x:"abc2", y1:"6",  y2:"-2", y3:"-3" },
                   {x:"abc3", y1:"-3", y2:"-9", y3:"4"}]

var data = ["y1","y2","y3"].map(
        return  {y: +d[v]};

Then, most of the original code can be used as-is.

Another part which you can adapt is the domain for the x-scale

x = d3.scale.ordinal()
        .rangeRoundBands([margin,w-margin], .1)

The group names are hard coded, but you have them in your objects as "x".

Instead, we can automatically use the x value of each object as the label for each set:

x = d3.scale.ordinal()
    .domain({return d.x}))
    .rangeRoundBands([margin,w-margin], .1)

Putting it all together, with some extra values:

The other option is to rewrite the code to bind the data as-is, but you will need to understand how the stacked bar chart is built and then adapt it to your original JSON.


You have a couple of options:

  1. Is to provide the data from the server side to make it look like the JSON structure that graph likes.
  2. You can parse through your JSON on the client side and make a new JSON
  3. You can modify the graph chart such that it will work with your JSON

Related Query

More Query from same tag