简体   繁体   中英

D3 metadata on nodes

I am following this tutorial for a fore-directed graph, http://bl.ocks.org/mbostock/1153292 . I was wondering, how do you pass meta-data / user defined data to the d3 node and keep it around for later actions.

Example:

A user clicks on a node, and a table appears with the relevant meta-data attached to the node, such as label, alerts, comments, and other data that is not specifc to the d3 node/edge architecture.

You can pass whatever data you need to d3 and it will automatically store it on the node based on the nodes data function. Whether you use that data to populate nodes and edges is really up to you.

Here's a basic pie chart (note I'm leaving out the pie and arc definitions for brevity). In this example, data contains the information needed to build the pie chart. These get initially stored on the svg node and then each array element gets stored on the corresponding arc node. This data can contain whatever information you want. I use it to store a name and css class that I then apply to the pie wedges. However it can contain as rich of data as you need.

var data = [
  { name: 'Schedule slip', classname: 'c', value: 5},
  { name: 'Slightly behind', classname: 'b', value: 10},
  { name: 'On track', classname: 'a', value: 20}

];

  // select the svg element if it exists
  var svg = d3.selectAll('svg').data([data]);

  // otherwise create the skeletal chart
  var svgEnter = svg.enter().append('svg');

  // chart skeleton
  var gEnter = svgEnter.append('g').attr('class', 'donut');
  gEnter.append('g').attr('class', 'arcs');

  // Dimensions
  var width = (2 * outerRadius) + margin.left + margin.right,
      height = (2 * outerRadius) + margin.top + margin.bottom,
      hCenter = width/2,
      vCenter = height/2;

  svg
    .attr('width', width)
    .attr('height', height)
    .select('.donut')
      .attr('transform', translate(hCenter, vCenter));

    // draw the arcs
    var arcs = svg.select('.arcs').selectAll('.arc')
        .data(pie);  // compute pie wedge info and store it in arc node

    var gArc = arcs.enter().append('g').attr('class', 'arc');
    gArc.append('path').each(function(d) { this._current = d; });

    arcs.exit().remove();

    arcs.select('path')
        .attr('class', function(d) { return d.data.classname; })
      .transition().duration(500)
        .attrTween('d', arcTween);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM