0

I am trying to implement stacked bar chart. My data source is JSON array. Data might be negative or positive. I am referencing this link

http://bl.ocks.org/ZJONSSON/2975320

But the problem is the data used here like matrix type. like :

var data = [[{y:3},{y:6},{y:-3}],
            [{y:4},{y:-2},{y:-9}],
            [{y:10},{y:-3},{y:4}]
           ]

I have same data but in JSON array like :

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

Now my question is how I can implement this graph with JSON formatted data.

Phrogz
  • 296,393
  • 112
  • 651
  • 745
goldenbutter
  • 575
  • 2
  • 12
  • 25
  • 1
    I'm not sure I understand the question. Either of the code blocks you posted could be represented in [JSON](http://json.org/). Why would you want the property values to be strings instead of numbers? – Matt Kantor May 08 '13 at 21:46
  • You can have a look at this answer too: http://stackoverflow.com/questions/15388481/d3-js-histogram-with-positive-and-negative-values/15391554#15391554 – Christopher Chiche May 09 '13 at 04:57

2 Answers2

1

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(
    function(v){
      return initialData.map(function(d){
        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()
        .domain(['abc','abc2','abc3'])
        .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(initialData.map(function(d){return d.x}))
    .rangeRoundBands([margin,w-margin], .1)

Putting it all together, with some extra values: http://jsfiddle.net/fLMAZ/1/

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.

minikomi
  • 8,363
  • 3
  • 44
  • 51
0

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
theswiss
  • 92
  • 1
  • 4