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

大憨熊 提交于 2019-12-22 08:38:13

问题


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

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.


回答1:


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; });


来源:https://stackoverflow.com/questions/10526388/how-to-attach-properties-other-than-x-y-y0-to-a-layer-of-streamgraph-in-d3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!