使用新数据重绘d3图表

时间:2016-01-18 05:25:20

标签: javascript jquery d3.js graph

我是d3绘图的新手,我正在尝试使用收集的数据绘制d3节点和边缘图,并根据所选人员的名称更改图表。 drawn graph for the initial time when first refresh happened

the graph drawn after selecting another persons data instead of the previous one

  /*
    Selecting a person from a option box default a person is selected. Therefore default grapgh id perfectly drawn but if somebody is selected later, the graph is not drawn but it stucks at a corner of the svg
    */

  $("#select-person").change(function(io) {


    drawGraph(top3, 3, dasIp);
    //top3 is a array of names of people
  });



  function drawGraph(topPeople, n, dasIp) {
    //radius --> retweet   color-->content
    //d3.select("#d3graph").select("svg").remove();
    var graph = {
      "nodes": [{
          "name": "Myriel",
          "group": 1
        }, {
          "name": "Napoleon",
          "group": 1
        }, {
          "name": "Mlle.Baptistine",
          "group": 1
        }, {
          "name": "Mme.Magloire",
          "group": 1
        }, {
          "name": "CountessdeLo",
          "group": 1
        }, {
          "name": "Geborand",
          "group": 1
        }, {
          "name": "Champtercier",
          "group": 1
        }, {
          "name": "Cravatte",
          "group": 1
        }, {
          "name": "Count",
          "group": 1
        }, {
          "name": "OldMan",
          "group": 1
        }, {
          "name": "Labarre",
          "group": 2
        },

        {
          "name": "Champmathieu",
          "group": 2
        }, {
          "name": "Brevet",
          "group": 2
        }, {
          "name": "Chenildieu",
          "group": 2
        },


        ..... {
          "name": "Brujon",
          "group": 4
        }, {
          "name": "Mme.Hucheloup",
          "group": 8
        }
      ],
      "links": [{
          "source": 1,
          "target": 0,
          "value": 1
        }, {
          "source": 2,
          "target": 0,
          "value": 8
        }, {
          "source": 3,
          "target": 0,
          "value": 10
        }, {
          "source": 3,
          "target": 2,
          "value": 6
        }, {
          "source": 4,
          "target": 0,
          "value": 1
        },

        .....

        {
          "source": 76,
          "target": 58,
          "value": 1
        }
      ]
    };


    var g = graphlibDot.read("digraph { A -> B;}");

    var graph = new Object();
    var map = new Object();
    var index = 0;

    var linkIndex = 0;
    var Nodes = [];
    var Edges = [];
    var dataN1 = [],
      dataN2 = [],
      dataN3 = [];
    var dataE1 = [],
      dataE2 = [],
      dataE3 = [];



    var width = $("#d3graph").width();
    var height = $("#d3graph").height();

    d3.select("#d3graph").selectAll("svg").remove();
    var svg = d3.select("#d3graph").append("svg")
      .attr("width", width)
      .attr("height", height);


    `enter code here` // tool tip with the label
    var tip = d3.tip()
      .attr('class', 'd3-tip')
      .offset([-10, 0])
      .html(function(d) {
        return d.name + "";
      })
    svg.call(tip);

    svg.append("defs").selectAll("marker")
      .data(["suit", "licensing", "resolved"])
      .enter().append("marker")
      .attr("id", function(d) {
        return d;
      })
      .attr("viewBox", "0 -5 10 10")
      .attr("refX", 25)
      .attr("refY", 0)
      .attr("markerWidth", 6)
      .attr("markerHeight", 6)
      .attr("orient", "auto")
      .append("path")
      .attr("d", "M0,-5L10,0L0,5 L10,0 L0, -5")
      .style("stroke", "#4679BD")
      .style("opacity", "0.6");

    var tableNodes = [],
      tableEdges = [];
    for (var t = 0; t < n; t++) {
      var tn = topPeople[t].name + "NODETWEETTABLE";
      tableNodes.push(tn);
      var te = topPeople[t].name + "EDGETWEETTABLE"
      tableEdges.push(te);

    }
    console.log(tableNodes);
    console.log(tableEdges);


    var tableColor = ["#3dff4f", "#0042b3", "#ff4533"];
    var nodeUrl1, nodeUrl2, nodeUrl3, edgeUrl1, edgeUrl2, edgeUrl3;

    function() {

      //Here data is successfully recieved from the ajax calls in the format of
      /*
                         Data Format NAMEEDGESTWEETTABLE
                        ================
                        source -STRING
                        target -STRING
                        value -INT

                        Data Format NAMENODESTWEETTABLE
                        ================
                        name  -STRING
                        group -INT
                        degree - INT decide size of the vertex


                         */

      loadNodeData(Nodes, dataN1, dataN2, dataN3);
      loadEdgesData(Edges, dataE1, dataE2, dataE3);
      renderNodesEdges(Nodes, Edges);

    }

    function loadNodeData(Nodes, dataN1, dataN2, dataN3) {
      for (var i = 0; i < dataN1.length; i++) {
        var d = dataN1[i].values;
        d.color = tableColor[0];
        Nodes.push(d);


      }
      for (var i = 0; i < dataN2.length; i++) {
        var d = dataN2[i].values;
        d.color = tableColor[1];
        Nodes.push(d);


      }
      for (var i = 0; i < dataN3.length; i++) {
        var d = dataN3[i].values;
        d.color = tableColor[2];
        Nodes.push(d);


      }


    }

    function loadEdgesData(Edges, dataE1, dataE2, dataE3) {
      for (var i = 0; i < dataE1.length; i++) {
        var d = dataE1[i].values;
        Edges.push(d);

      }
      for (var i = 0; i < dataE2.length; i++) {
        var d = dataE2[i].values;
        Edges.push(d);

      }
      for (var i = 0; i < dataE3.length; i++) { //
        var d = dataE3[i].values;
        Edges.push(d);

      }

    }

    function renderNodesEdges(dataset1, dataset2) {
      dataset1.forEach(function(d) {

        map[d.name] = index;
        d.degree = parseInt(d.degree)
        index++;
      });

      graph.nodes = dataset1;

      dataset2.forEach(function(d) {


        var s = map[d.source];
        var t = map[d.target];

        if (typeof s === "undefined" || typeof t === "undefined") {

          d.source = 1
          d.target = 2;



        } else {
          d.source = map[d.source];
          d.target = map[d.target];
          d.value = parseInt(d.value)
        }
      });

      graph.links = dataset2;
      console.log("both loaded 2");
      drapGraph(graph);



    }



    function drapGraph(graph) {
      svg.selectAll(".link").remove();
      svg.selectAll(".gnode").remove();
      var force = d3.layout.force()
        .charge(-120)
        .linkDistance(20)
        .size([width, height])
        .nodes(graph.nodes)
        .links(graph.links)
        .start();

      var rScale = d3.scale.linear()
        .domain([d3.min(graph.nodes, function(d) {
          return Math.log(d.group);
        }), d3.max(graph.nodes, function(d) {
          return Math.log(d.group);
        })])
        .range([0, 30]);

      var link = svg.selectAll(".link")
        .data(graph.links)
        .enter().append("line")
        .attr("class", "link")
        .style("stroke-width", 2)
        .style("stroke-length", function(d) {
          return (10000 / d.value);
        });
      var node = svg.selectAll(".gnode")
        .data(graph.nodes)
        .enter().append("g")
        .attr("class", "gnode")
        .on('mouseover', tip.show)
        .on('mouseout', tip.hide)
        .call(force.drag);

      var maxretweets = d3.max(graph.nodes, function(d) {
        return Math.log(d.group);
      });
      var minretweets = d3.min(graph.nodes, function(d) {
        return Math.log(d.group);
      });
      var maxContent = d3.max(graph.nodes, function(d) {
        return d.degree;
      });
      var minvalue = d3.min(graph.links, function(d) {
        return d.value;
      });

      var circle = node.append("circle")
        .attr("r", function(d) {
          return rScale(Math.log(d.group));
        })
        .style("fill", function(d) {
          return d.color;

        })
        .style("stroke", "#000000");

      var label = node.append("text")
        .style("font-family", "sans-serif")
        .style("text-anchor", "middle")
        .style("font-size", "8")
        .style("stroke", "#404040")
        .text(function(d) {

          if (rScale(Math.log(d.group)) > 20) {
            return d.name;
          }
        });

      node.append("title")
        .text(function(d) {
          return d.name;
        });

      force.on("tick", function() {
        link.attr("x1", function(d) {
            return d.source.x;
          })
          .attr("y1", function(d) {
            return d.source.y;
          })
          .attr("x2", function(d) {
            return d.target.x;
          })
          .attr("y2", function(d) {
            return d.target.y;
          });

        node.attr("cx", function(d) {
            return d.x;
          })
          .attr("cy", function(d) {
            return d.y;
          });

        enter code here circle.attr("cx", function(d) {
            return d.x;
          })
          .attr("cy", function(d) {
            return d.y;
          });

        label.attr("x", function(d) {
            return d.x;
          })
          .attr("y", function(d) {
            return d.y;
          });




      });




    }


  }
<div class="col-xs-6 col-md-4">
  <div id="d3graph" style="width: 500px; height: 400px;" class="container">

  </div>

</div>

从选项框中选择默认人员,因此在页面加载时,将绘制默认人员的图表。但是当再次调用选项框的.onChange()时,图形不会被绘制,但它会粘在角落,如上图所示。数据完全来自ajax调用。

有人可以帮我解决代码中的问题吗?

1 个答案:

答案 0 :(得分:0)

您的行d3.select("#d3graph").selectAll("svg").remove();似乎应该工作。当图形太复杂而无法向其追加数据时,我就是这样做的。