javascriptjsond3.jsstream-graph

How to attach properties other than x,y,y0 to a layer of streamgraph in d3?


I am a d3 newbie and I've been trying to customize the Streamgraph example (http://mbostock.github.com/d3/ex/stream.html):

enter image description here

I have run into some issues:

I want to assign a custom data property (for examples sake, lets just say its a label called "type") to each layer in the stream so that when you hover over that layer, a popup box appears with the "type" listed for that layer.

When I input my data source into the graph I use this code:

      vis.selectAll("path")
        .data(data0)
      .enter().append("path")

The graph only seems to take data of the format:

            [
                 [
                    {
                        "x": 0,
                        "y": 91,
                        "y0": 1.11
                    },
                    {
                        "x": 1,
                        "y": 290,
                        "y0": 1.11
                    }
                ],  
                [
                    {
                        "x": 0,
                        "y": 9,
                        "y0": 1.11
                    },
                    {
                        "x": 1,
                        "y": 49,
                        "y0": 1.11
                    }
                 ]
             ]

Where each sub-array above corresponds to a layer in the streamgraph.

How can I pass data to the graph that allows me to add an extra "type" property for each layer?

Basically so that when I refer to the datum of a layer, I can just type something like d.type and extract that property?

I originally came up with a really hackish way to do it:

                [
                    {
                        "x": 0,
                        "y": 9,
                        "y0": 1.11,
                        "type": "listings"
                    },
                    {
                        "x": 1,
                        "y": 49,
                        "y0": 1.11,
                    }
                 ]

and then I refer to it in the layer datum by saying d[0].type, but this doesn't seem like the proper way to do it.


Solution

  • Use stack.values, and then wrap each layer's data points with some additional data for the layer. Your data will look something like this:

    [
      {
        "type": "apples",
        "values": [
          { "x": 0, "y":  91},
          { "x": 1, "y": 290}
        ]
      },
      {  
        "type": "oranges",
        "values": [
          { "x": 0, "y":  9},
          { "x": 1, "y": 49}
        ]
      }
    ]
    

    And the stack layout like this:

    var stack = d3.layout.stack()
        .offset("wiggle")
        .values(function(d) { return d.values; });